A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/node-js/node-js-callback-concept/ below:

Node Callback Concept - GeeksforGeeks

Node Callback Concept

Last Updated : 12 Jul, 2025

A callback in Node is a non-blocking function that executes upon task completion, enabling asynchronous processing. It facilitates scalability by allowing Nodejs to handle multiple requests without waiting for operations to conclude, as exemplified in file I/O scenarios.

Explanation: The fs library is used for file-system operations. The readFileSync() function is synchronous, halting program execution until completion. This blocking behavior ensures that the program reads the file before progressing further.

Example 1: Code for reading a file synchronously (blocking code) in Nodejs. Create a text file inputfile1.txt with the following content:

Hello Programmer!!!
Learn NodeJS with GeeksforGeeks
JavaScript
// Write JavaScript code
const fs = require("fs");
const filedata = fs.readFileSync('inputfile1.txt');
console.log(filedata.toString());
console.log("End of Program execution");

Output:

Explanation: The fs library is utilized for file-system operations. The asynchronous readFile() function allows the program to proceed immediately to the next instruction while the task runs in the background. A callback function is employed to execute upon the completion of the background task.

Example 2: Code for reading a file asynchronously (non-blocking code) in Nodejs. Create a text file inputfile1.txt with the following content.

Hello Programmer!!!
Learn NodeJS with GeeksforGeeks
JavaScript
// Write a JavaScript code
const fs = require("fs");

fs.readFile('inputfile1.txt',
    function (ferr, filedata) {
        if (ferr) return console.error(ferr);
        console.log(filedata.toString());
    }
);
console.log("End of Program execution");

Output:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4