Blocking and Non-Blocking Calls in NodeJS

Mohan pd.
Written by Mohan pd. on
Blocking and Non-Blocking Calls in NodeJS

NodeJS is famous due to its non-blocking nature. Here are the key difference between blocking and non-blocking calls.

  • Blocking methods execute synchronously and non-blocking methods execute asynchronously
  • Execution of additional JS in Nodejs process must wait until the execution of non-JS operation completes (blocking operation)
  • It happens because the event loop is unable to run JS code until blocking operation completes
  • Most commonly used synchronous methods are from NodeJS library
  • All I/O methods in Nodejs standard library have asynchronous versions which are non-blocking and accept callback functions

Example of Synchronous file read:

const fs = require('fs');
const data = fs.readFileSync('/'); // blocks here until file is read
// moreWork(); will run after console.log

Example of Asynchronous file read:

const fs = require('fs');
fs.readFile('/', (err, data) => \{ if (err) throw err; console.log(data); \});
// moreWork(); will run before console.log


JavaScript execution in Node.js is single-threaded, so concurrency refers to the event loop’s capacity to execute JavaScript callback functions after completing other work. Any code that is expected to run concurrently must allow the event loop to continue running as non-JavaScript operations, like I/O, are occurring.

Mohan pd.

Mohan pd.

Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.


comments powered by Disqus