Understanding the Event driven code execution approach in Node

Node.jsServer Side ProgrammingProgramming

In earlier example in App.js , we saw how to parse data from request using data and end event.

Code snippet below shows the if block for that −

if(url === '/username' && req.method === 'POST'){
   const requestBody = [];
   req.on('data', (chunks)=>{
      requestBody.push(chunks);
   });
   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();
}

In above code block, we have two events (data and end) registered if path matches to ‘/username’ and method is post. The execution order of these two events is handled internally by node.js. The other statements below the if block will be executed immediately once event registration is completed by node.js

We have return statement outside the end event like below −

//redirect
res.statusCode=302;
res.setHeader('Location','/');
return res.end();

If we add return move the return statement inside the end event, there is possibility that the other statement below if block will get executed before completion of end event. This is because the code execution in end event will be completed at later time internally by node.js

Error if return statement is incorrectly placed −

Error says once we returned response , we should not modify it. Other statement below if block gets executed first then our end event also tries in last to modify response which results into error as shown above.

Solution to handle above error −

1. We can add return statement inside the if block instead of event code function :

2. if(url === '/username' && req.method === 'POST'){
3.
4.    const requestBody = [];
5.    req.on('data', (chunks)=>{
6.       requestBody.push(chunks);
7.    });
8.
9.    req.on('end', ()=>{
10.      const parsedData = Buffer.concat(requestBody).toString();
11.      const username = parsedData.split('=')[1];
12.      fs.writeFileSync('username.txt', username);
13.
14.   });
15.
16.    //redirect
17.    res.statusCode=302;
18.    res.setHeader('Location','/');
19. return res.end();
20.
21. }

2. We can add return statement to entire end event function −

if(url === '/username' && req.method === 'POST'){
   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();
   });
}

Event code execution works in asynchronous and developers will have to carefully write the return logic for responses.

raja
Published on 13-May-2020 11:59:18
Advertisements