# 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();
//redirect res.statusCode=302;
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();
console.log(error);
});
//redirect res.statusCode=302;
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.

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