WikiGalaxy

Personalize

Callback Functions in Node.js

Introduction to Callbacks

Callbacks are functions passed as arguments to other functions, allowing code to be executed later. They are essential in Node.js for handling asynchronous operations.

Handling Asynchronous Operations

In Node.js, callbacks are used to handle asynchronous tasks like reading files, making HTTP requests, and interacting with databases.

Error-First Callback Pattern

Node.js follows an error-first callback pattern, where the first argument of a callback is an error object, and the second is the result.


const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log(data);
});
        

Reading Files Asynchronously

The fs.readFile method reads a file asynchronously. It takes a callback function that handles the error and the file data.

Error Handling

If an error occurs during the file read operation, it is passed to the callback and logged using console.error.

Logging File Data

If the file is read successfully, its contents are logged to the console.

Console Output:

Contents of file.txt

Promises in Node.js

Introduction to Promises

Promises are objects representing the eventual completion or failure of an asynchronous operation, providing a cleaner alternative to callbacks.

Promise States

A promise can be in one of three states: pending, fulfilled, or rejected.

Chaining Promises

Promises can be chained using the .then() and .catch() methods, allowing for sequential execution of asynchronous tasks.


const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
    .then(data => {
        console.log(data);
    })
    .catch(err => {
        console.error(err);
    });
        

Using Promises with fs Module

The fs.promises.readFile method returns a promise that resolves with the file data or rejects with an error.

Handling Fulfillment

The .then() method is used to handle the fulfilled state of the promise, logging the file data to the console.

Handling Rejection

The .catch() method is used to handle the rejected state of the promise, logging any errors that occur.

Console Output:

Contents of file.txt

Converting Callbacks to Promises

Utilizing util.promisify

The util.promisify function in Node.js can convert callback-based functions to promise-based ones, simplifying asynchronous code.

Example: Promisifying fs.readFile

By promisifying fs.readFile, you can use it with promises instead of callbacks, making the code more readable.


const fs = require('fs');
const util = require('util');
const readFilePromise = util.promisify(fs.readFile);

readFilePromise('file.txt', 'utf8')
    .then(data => {
        console.log(data);
    })
    .catch(err => {
        console.error(err);
    });
        

Using Promisified Functions

The promisified readFilePromise function returns a promise, allowing you to handle asynchronous operations with .then() and .catch().

Improved Readability

Converting callbacks to promises improves code readability by eliminating deeply nested callback structures.

Console Output:

Contents of file.txt

Async/Await in Node.js

Introduction to Async/Await

Async/await is a syntax for working with promises, making asynchronous code look synchronous and easier to read.

Using Async Functions

An async function returns a promise and allows the use of the await keyword to pause execution until a promise is resolved.


const fs = require('fs').promises;

async function readFileAsync() {
    try {
        const data = await fs.readFile('file.txt', 'utf8');
        console.log(data);
    } catch (err) {
        console.error(err);
    }
}

readFileAsync();
        

Handling Asynchronous Code

The readFileAsync function uses the await keyword to pause execution until the promise returned by fs.readFile is resolved.

Error Handling with Try/Catch

Errors are handled using a try/catch block, providing a synchronous-looking error handling approach.

Console Output:

Contents of file.txt

Parallel Execution with Promises

Executing Promises in Parallel

Using Promise.all, multiple promises can be executed in parallel, improving performance by running tasks concurrently.

Handling Multiple Files

This technique is useful for reading multiple files or making multiple HTTP requests simultaneously.


const fs = require('fs').promises;

Promise.all([
    fs.readFile('file1.txt', 'utf8'),
    fs.readFile('file2.txt', 'utf8')
])
.then(([data1, data2]) => {
    console.log(data1);
    console.log(data2);
})
.catch(err => {
    console.error(err);
});
        

Using Promise.all

The Promise.all method takes an array of promises and returns a single promise that resolves when all input promises have resolved.

Efficient File Reading

This approach allows for efficient reading of multiple files, with results available as an array in the .then() method.

Console Output:

Contents of file1.txt

Contents of file2.txt

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025