What is Blocking?
It refers to the blocking of further operation until the current operation finishes. Blocking methods are executed synchronously. Synchronously means that the program is executed line by line. The program waits until the called function or the operation returns.
Example: Following example uses the readFileSync() function to read files and demonstrate Blocking in Node.js
Javascript
const fs = require( 'fs' ); const filepath = 'text.txt' ; // Reads a file in a synchronous and blocking way const data = fs.readFileSync(filepath, {encoding: 'utf8' }); // 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:
This is from text file.
Sum: 55
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