Understanding blocking and unblocking of code execution in Node


Now, we have a file writing function writeFileSync in fs module as shown below −

const requestBody = [];
req.on('data', (chunks)=>{
   requestBody.push(chunks);
});
return req.on('end', ()=>{
   const parsedData = Buffer.concat(requestBody).toString();
   const username = parsedData.split('=')[1];
   fs.writeFileSync('username.txt', username);
   //redirect res.statusCode=302;
   res.setHeader('Location','/');
   return res.end();
});

Sync means synchronized. It’s a blocking code example. Once file write is completed then only code execution for rest of the file starts. Above code is simpler but if we have a large file handling operation it will result into slow performance of app.

This way of code execution will slow down the other requests and eventually performance of application.

Solution to this problem is to use asynchronous function of file writing. We have writeFile in fs module which is asynchronous. Below is the example for it −

return req.on('end', ()=>{
   const parsedData = Buffer.concat(requestBody).toString();
   const username = parsedData.split('=')[1];
   fs.writeFile('username.txt', username, (error)=>{
      console.log(error);
   });
   //redirect res.statusCode=302;
   res.setHeader('Location','/');
   return res.end();
});

writeFile takes one more argument i.e. error object. If there is any error in completing the file handling function we can check it with error in console.

This way we can avoid the code blocking. In file handling Node js can use the operating systems multithreading approach to give better performance. It just registers the events and executes them later at specific points.

Asynchronous is most used way of handling operations in node.js like fetching data from server , manipulating the data , pagination etc.

readFile and readFileSync

similar to write file functions we have read files functions which are also categorized into blocking and non-blocking way.

readFile is non-blocking and readFileSync is blocking. We can use promises to handle operations which are yet to complete but will respond with some resolve once done .

PromiseOperationFunction()
.then( ()=> console.log(‘completed with succes’); )
.catch((err)=> console.log(‘completed with failure’); );

Updated on: 13-May-2020

436 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements