What is Non-Blocking ?
It refers to the program that does not block the execution of further operations. Non-Blocking methods are executed asynchronously. Asynchronously means that the program may not necessarily execute line by line. The program calls the function and move to the next operation and does not wait for it to return.
Example: Following example uses the readFile() function to read files and demonstrate Non-Blocking in Node
Javascript
const fs = require( 'fs' ); const filepath = 'text.txt' ; // Reads a file in a asynchronous and non-blocking way fs.readFile(filepath, {encoding: 'utf8' }, (err, data) => { // Prints the content of file console.log(data); }); // This section calculates the sum of numbers from 1 to 10 let sum = 0; for (let i=1; i<=10; i++){ sum = sum + i; } // Prints the sum console.log( 'Sum: ' , sum); |
Run the index.js file using the following command:
node index.js
Output:
Sum: 55
This is from text file.
Explanation: In the non-blocking program the sum actually prints before the content of the file. This is because the program does not wait for the readFile() function to return and move to the next operation. And when the readFile() function returns it prints the content.
Blocking and Non-Blocking in Node
Node is based on an event-driven non-blocking I/O model. This article discusses what does Blocking and Non-Blocking in Node means.
Table of Content
- What is Blocking?
- What is Non-Blocking ?
- How Concurrency and throughput is handled?
- Drawback of mixing Blocking and Non-Blocking Code
Contact Us