a blog for those who code

Monday 11 July 2016

How to execute a function immediately after HTTP response is sent in Node.js

In this post we will be discussing about executing a function immediately after HTTP response is sent successfully in Node.js. Lets say you have a scenario where you want to execute some code immediately after successful completion of request, i.e. response send successfully.

We will be using Response (a.k.a res) object which represents the HTTP response that an Express application sends when it gets HTTP request. For example :

app.get('/', function(req, res) {
  res.send('Hello World');

ALSO READ : Difference between res.send and res.json in Express.js

In the above example along with sending a response lets say you want to send email which can be achieved from the below code :

app.get('/', function(req, res) {
  res.on('finish', function() {
    console.log('Finished With Status : ' res.statusCode);
    //code to send email

You can also use response.end() along with the callback as shown below :

app.get('/', function(req,res) {
  res.end('', callback) 

ALSO READ : How to handle HTTP requests in Node.js Application

In the callback you can write your code to send email where if callback is specified it will be called when the request is finished.

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment