Category: Example

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRPa0sWOypU8K61mdPRlCT0wpSsu8mXEMdg6Q&s

  • Using worker_threads for Parallel Processing

    Node.js 12 introduced the worker_threads module, allowing for parallel execution of JavaScript.

    javascriptCopy code// worker.js
    const { parentPort } = require('worker_threads');
    
    parentPort.on('message', (data) => {
    
    // Perform some computation
    parentPort.postMessage(data * 2);
    }); // main.js const { Worker } = require('worker_threads'); function runWorker(data) {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./worker.js');
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.postMessage(data);
    });
    } async function main() {
    try {
        const result = await runWorker(5);
        console.log('Worker result:', result);
    } catch (err) {
        console.error('Worker error:', err);
    }
    } main();

    Explanation:

    • worker_threads allows you to create parallel threads for computation.
    • Use postMessage to communicate between the main thread and worker threads.
  • Using the fs.promises API

    Node.js 10 introduced the fs.promises API, providing a promise-based approach to file system operations.

    javascriptCopy code// Example using fs.promises for file operations
    const fs = require('fs').promises;
    
    async function manageFile() {
    
    try {
        await fs.writeFile('./example.txt', 'Hello, Node.js!');
        const data = await fs.readFile('./example.txt', 'utf8');
        console.log('File content:', data);
        await fs.unlink('./example.txt');
        console.log('File deleted.');
    } catch (err) {
        console.error('Error managing file:', err);
    }
    } manageFile();

    Explanation:

    • Perform file operations (write, read, delete) using the promise-based fs.promises API.
  • Working with ES6 Modules

    Node.js 12 introduced support for ES6 modules, allowing the use of import and export syntax natively.

    javascriptCopy code// example.js
    export function greet(name) {
    
    return Hello, ${name}!;
    } // app.mjs import { greet } from './example.js'; console.log(greet('World'));

    Explanation:

    • Use the .mjs extension for ES6 modules or set "type": "module" in package.json.
    • Import and export functions using ES6 module syntax.
  • Streams for Large Data Processing

    Streams in Node.js are ideal for processing large amounts of data in chunks, rather than loading it all into memory at once.

    javascriptCopy code// Example using streams to read a large file
    const fs = require('fs');
    const readline = require('readline');
    
    const fileStream = fs.createReadStream('./largeFile.txt');
    const rl = readline.createInterface({
    
    input: fileStream,
    crlfDelay: Infinity
    }); rl.on('line', (line) => {
    console.log(Line from file: ${line});
    }); rl.on('close', () => {
    console.log('File read complete.');
    });

    Explanation:

    • fs.createReadStream creates a readable stream for a large file.
    • readline.createInterface processes each line from the stream.
  • Using the http Module with Promises

    Node.js 10 introduced improvements to the http module, making it easier to work with HTTP requests and responses.

    javascriptCopy code// Example using http module with async/await
    const http = require('http');
    
    function request(url) {
    
    return new Promise((resolve, reject) => {
        http.get(url, (response) => {
            let data = '';
            response.on('data', (chunk) => data += chunk);
            response.on('end', () => resolve(data));
        }).on('error', reject);
    });
    } async function fetchData() {
    try {
        const data = await request('http://www.example.com');
        console.log(data);
    } catch (err) {
        console.error('Error fetching data:', err);
    }
    } fetchData();

    Explanation:

    • Wrap the http.get function in a Promise to use with async/await.
  • Async/Await for Asynchronous Operations

    With the introduction of async/await in Node.js, handling asynchronous operations has become more readable and maintainable compared to traditional callback-based methods.

    javascriptCopy code// Example using async/await
    const fs = require('fs').promises;
    
    async function readFile(filePath) {
    
    try {
        const data = await fs.readFile(filePath, 'utf8');
        console.log(data);
    } catch (err) {
        console.error('Error reading file:', err);
    }
    } readFile('./example.txt');

    Explanation:

    • fs.promises provides promise-based versions of filesystem methods.
    • async/await is used to handle the asynchronous readFile method more cleanly.