nodejs Callback Concept (Practically Explained)


A server receives [request-one], [request-two, [request-three]. A traditional server will process [request-one], wait for it to finish before processing [request-two] in like fashion as [request-three].
In nodejs, it a different concept. nodejs receive and process multiple requests simultaneously. This makes nodejs highly scalable, as it can process a high number of requests.

A function starts reading a file return the control to execution immediately so that the next instruction can be executed. One file reading is complete, it will call the callback function. So there is no waiting or wait for the File System.

Blocking Code Example

creates a text file [input.txt] and writes some text in there.
touch input.txt
add the following text
I am learning nodejs callback concept.
create another file main.js and add the following code
const fileSystem = require('fs');
// use the file system module to read our sample.txt file Synchronously.
const file = fileSystem.readFileSync('sample.txt');

// log out the file on the console.
console.log(file.toString());
console.log("program ended.");

run the above code.
node main.js
result
I am learning nodejs callback concept.
program ended.

Non-Blocking Code Example

In the file main.js, I will change the reading of the file from readFileSync to readFile.
const fileSystem = require('fs');
// use the file system module to read our sample.txt file Asynchronously.
fileSystem.readFile('sample.txt',(errorfile)=> {
    if(error){
        return console.error(error);
    }else{
        console.log(file.toString());
    }
})

console.log("program ended.");

run the above code.
program ended.
I am learning nodejs callback concept.

The first example shows the program blocks until the reading of the file is completed.
The second example shows the program does not wait for the reading of the file and proceed.
Thus, a blocking program executes much in in sequence.

Post a Comment

0 Comments