# v8

***

**1. Server-Side Rendering (SSR)**

```javascript
const express = require('express');
const path = require('path');

const app = express();

app.get('/', async (req, res) => {
  const { renderToString } = require('react-dom/server');
  const App = require('./App.js').default;

  const html = renderToString(<App />);

  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>My App</title>
      </head>
      <body>
        <div id="root">${html}</div>
        <script src="./client.js"></script>
      </body>
    </html>
  `);
});

app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000);
```

**2. Client-Side Routing**

```javascript
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
        </ul>

        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </div>
    </Router>
  );
}

function Home() { return <h1>Home</h1>; }
function About() { return <h1>About</h1>; }
function Contact() { return <h1>Contact</h1>; }

export default App;
```

**3. Asynchronous Programming**

```javascript
const fs = require('fs');

const readFileAsync = async (path) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

readFileAsync('file.txt').then((data) => {
  console.log(data);
}).catch((err) => {
  console.error(err);
});
```

**4. Database Connectivity (MongoDB)**

```javascript
const MongoClient = require('mongodb').MongoClient;

const client = new MongoClient('mongodb://localhost:27017');

async function connect() {
  await client.connect();
  const db = client.db('my-database');
  const collection = db.collection('my-collection');

  const result = await collection.insertOne({ name: 'John Doe' });
  console.log(`A document was inserted with the _id: ${result.insertedId}`);
}

connect().catch(console.error);
```

**5. WebSockets**

```javascript
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log(`Received a message: ${message}`);
    ws.send(`Hello, ${message}!`);
  });
});
```

**6. Image Processing**

```javascript
const sharp = require('sharp');

sharp('input.jpg')
  .resize(200, 200)
  .toFile('output.jpg', (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log(`Image resized to ${info.width}x${info.height}`);
    }
  });
```

**7. Machine Learning (TensorFlow\.js)**

```javascript
const tf = require('@tensorflow/tfjs');

const model = tf.sequential();
model.add(tf.layers.dense({ units: 100, activation: 'relu', inputShape: [10] }));
model.add(tf.layers.dense({ units: 1, activation: 'sigmoid' }));

const xs = tf.randomNormal([100, 10]);
const ys = tf.randomUniform([100, 1]);

model.compile({ loss: 'meanSquaredError', optimizer: 'adam' });
model.fit(xs, ys, { epochs: 100 }).then(() => {
  console.log('Model trained!');
});
```

**8. Audio Processing**

```javascript
const Speaker = require('speaker');

const speaker = new Speaker({
  channels: 2,          // 2 channels
  bitDepth: 16,         // 16-bit samples
  sampleRate: 44100     // 44,100 Hz sample rate
});

speaker.write('Hello, world!');
```

**9. Video Processing**

```javascript
const ffmpeg = require('fluent-ffmpeg');

ffmpeg('input.mp4')
  .output('output.mp4')
  .videoCodec('libx264')
  .audioCodec('aac')
  .saveToFile((err) => {
    if (err) {
      console.error(err);
    } else {
      console.log('Video transcoded!');
    }
  });
```

**10. Performance Analysis**

```javascript
const util = require('util');

const benchmark = async () => {
  const start = process.hrtime();
  await Promise.all([
    // Run multiple asynchronous tasks
  ]);
  const end = process.hrtime(start);

  console.log(`Benchmark took ${util.inspect(end, { depth: null })} seconds to complete.`);
};

benchmark();
```

**11. Unit Testing**

```javascript
const assert = require('assert');

const sum = (a, b) => a + b;

describe('Sum function', () => {
  it('should return the sum of two numbers', () => {
    assert.strictEqual(sum(1, 2), 3);
  });

  it('should return 0 when one of the numbers is 0', () => {
    assert.strictEqual(sum(0, 2), 0);
  });
});
```

**12. End-to-End Testing**

```javascript
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('https://example.com');
  await page.screenshot({ path: 'screenshot.png' });

  await browser.close();
})();
```

**13. Performance Profiling**

```javascript
const { performance } = require('perf_hooks');

const measurePerformance = (fn, ...args) => {
  const start = performance.now();
  const result = fn(...args);
  const end = performance.now();

  console.log(`Function took ${end - start} milliseconds to execute.`);

  return result;
};

measurePerformance(sum, 1, 2);
```

**14. Code Coverage**

```javascript
const nyc = require('nyc');

nyc.instrument({
  cwd: process.cwd(),
  all: true
});

require('./main.js');

nyc.report();
```

**15. Static Code Analysis**

```javascript
const eslint = require('eslint');

const linter = new eslint.Linter();
const results = linter.verify('./main.js', {
  rules: {
    // Specify the rules to check
  }
});

results.map((result) => {
  console.log(`Line ${result.line}: ${result.message}`);
});
```

**16. Build Tooling (Webpack)**

```javascript
const webpack = require('webpack');

const config = {
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js'
  },
  module: {
    rules: [
      // Specify the loaders and rules for transpiling, linting, etc.
    ]
  },
  plugins: [
    // Specify the plugins for optimizing, etc.
  ]
};

webpack(config, (err, stats) => {
  if (err) {
    console.error(err);
  } else {
    console.log(stats.toString());
  }
});
```

**17. Test Runner (Mocha)**

```javascript
const assert = require('assert');
const Mocha = require('mocha');

const mocha = new Mocha();

mocha.addFile('./test.js');
mocha.run((failures) => {
  process.exitCode = failures ? 1 : 0;
});
```

**18. Debugger (Node.js Inspector)**

```javascript
const inspector = require('inspector');

inspector.open(9229, '0.0.0.0', true);
```

**19. REPL (Node.js REPL)**

```javascript
const repl = require('repl');

repl.start({ prompt: '> ' });
```

**20. Context Isolation**

```javascript
const vm = require('vm');

const context = vm.createContext({
  console: console
});

vm.runInContext('console.log("Hello, world!")', context);
```

**21. Sandboxing**

```javascript
const sandbox = require('sandbox');

const sandboxedFn = sandbox.compile('(a, b) => a + b', { timeout: 5000 });
console.log(sandboxedFn(1, 2));
```

**22. Native Add-ons**

```C++
#include <node.h>

namespace demo {

using Nan::New;
using Nan::Set;

NAN_METHOD(Hello) {
  info.GetReturnValue().Set(New<String>("Hello, world!").ToLocalChecked());
}

NAN_MODULE_INIT(Init) {
  Set(target, New<String>("hello").ToLocalChecked(),
      New<FunctionTemplate>(Hello)->GetFunction());
}

NODE_MODULE(addon, Init)

}  // namespace demo
```

**23. Internationalization**

```javascript
const i18n = require('i18n');

i18n.configure({
  locales: ['en', 'es'],
  defaultLocale: 'en',
  directory: path.join(__dirname, 'locales')
});

const message = i18n.__('Hello, world!');
console.log(message);
```

**24. HTTP Proxy**

```javascript
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer({});

httpProxy.web(request, response, { target: 'http://example.com' });
```

**25. WebSocket Proxy**

```javascript
const WebSocket = require('ws');
const httpProxy = require('http-proxy');

const wss = new WebSocket.Server({ port: 8080 });
const proxy = httpProxy.createProxyServer({ ws: true });

wss.on('connection', (ws, req) => {
  proxy.web(ws, req, { target: 'ws://example.com' });
});
```

**26. Rate Limiting**

```javascript
const rateLimit = require('express-rate-limit');

const app = express();

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

app.use(limiter);
```

**27. Authentication**

```javascript
const passport = require('passport');

const app = express();

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy((username, password, done) => {
  // Lookup the user in the database
  // ...

  // Return done(null, user) if the user is authenticated,
  // or done(null, false) if the user is not authenticated.
}));
```

**28. Caching**

```javascript
const redis = require('redis');

const client = redis.createClient();

client.set('key', 'value', (err, reply) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`Value set: ${reply}`);
  }
});

client.get('key', (err, reply) => {
  if (err) {
    console.error(err);
  } else {
    console.log(`Value fetched: ${reply}`);
  }
});
```

**29. Data Validation**

```javascript
const Ajv = require('ajv');

const ajv = new Ajv();

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' }
  },
  required: ['name', 'age']
};

const validate = ajv.compile(schema);

const data = { name: 'John Doe', age: 30 };

const valid = validate(data);
if (valid) {
  console.log('Data is valid');
} else {
  console.log('Data is invalid: ', validate.errors);
}
```

**30. Input Sanitation**

```javascript
const sanitizeHtml = require('sanitize-html');

const sanitizedHtml = sanitizeHtml('<script>alert("XSS")</script>');
console.log(`Sanitized HTML: ${sanitizedHtml}`);
```

**31. Output Escaping**

```javascript
const escapeHtml = require('escape-html');

const escapedHtml = escapeHtml('<script>alert("XSS")</script>');
console.log(`Escaped HTML: ${escapedHtml}`);
```

**32. Error Handling**

```javascript
try {
  // Code that may throw an error
} catch (error) {
  // Handle the error
} finally {
  // Code that will always run, regardless of whether an error was thrown
}
```

**33. Promises**

```javascript
const promise = new Promise((resolve, reject) => {
  // Code that may take some time to complete
  if (successful) {
    resolve('Success');
  } else {
    reject('Failure');
  }
});

promise.then((result) => {
  console.log(result);
}).catch((error) => {
  console.error(error);
});
```

**34. Async/Await**

```javascript
const fetch = require('node-fetch');

async function getGithubUser(username) {
  const response = await fetch(`https://api.github.com/users/${username}`);
  if (!response.ok) {
    throw new Error(`Error: ${response.status} ${response.statusText}`);
  }
  return await response.json();
}

getGithubUser('username').then((user) => {
  console.log(`User: ${user.name}`);
}).catch((error) => {
  console.error(error);
});
```

**35. Generators**

```javascript
function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

for (const num of fibonacci()) {
  console.log(num);
  if (num > 100) {
    break;
  }
}
```

**36. Streams**

```javascript
const fs = require('fs');

const readableStream = fs.createReadStream('input.txt');
const writableStream = fs.createWriteStream('output.txt');

readableStream.pipe(writableStream);
```
