js,

Blocking and Non-Blocking Calls in NodeJS

Mohan pd. Follow Sep 22, 2019 · 1 min read
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('/file.md'); // blocks here until file is read
console.log(data);
// moreWork(); will run after console.log

Example of Asynchronous file read:

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

Concurrency

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.

Join Newsletter
Get the latest news right in your inbox. We never spam!
Written by Mohan pd. Follow
comments powered by Disqus
The Coders Blog   Never miss a story from us, subscribe to our newsletter
Copyright © 2019 The Coders Blog