Global Events in NodeJS

 

       We have seen what events and event emitters are in NodeJS. Also we have seen how to create and use our own events. This article exposes you to some of the predefined events in NodeJS which play a crucial role in your application life cycle. 

Following are some of the global events in NodeJS.

Open server.js file and try the following codes to the working of each of the event. The following events are heard by the process global variable. To register a listener for an event, we use 

process.on(<event name>, liistenerFunction)                                                                                           

exit
This is an event which is emitted whenever a NodeJS process is terminating. It can be because the event loop senses that no threads are running or calling process.exit() function explicitly.


"use strict";

var i = 0;
setInterval(function(){
  console.log(i);
  i++;

  if(i==2){
    process.exit();
  }
  
}, 1000);

process.on('exit', function(code){
  console.log("Exiting: "+code);
});


SIGINT
        SIGINT stands for SIGNAL INTERRUPT. This event is triggered whenever the user interrupts a Node process by pressing Ctrl+C or Cmd+C (in Mac). The listener you define here will override the default functionality i.e. stopping the code. That is why we will add a process.exit() inside the listener else the process won’t ever stop by an interrupt.


"use strict";

var i = 0;
setInterval(function(){
  console.log(i);
  i++;
}, 1000);

process.on('SIGINT', function(){
  console.log("Exiting process");
  process.exit(0);
});


It will keep on printing integers unless we interrupt by pressing CTRL+C


On pressing Ctrl+C, our listener is executed which first prints out message defined in our listener. After this the process exists because of process.exit().

warning
       This event is emitted whenever the current NodeJS process emits a warning. You can emit a warning using process.emitWarning() function. This event is used by many database modules whenever some configuration mismatch has happened. You should use this instead of console.log() when developing some modules.


"use strict";

var i = 0;
setInterval(function(){
  console.log(i);
  i++;
  if(i==3){
    process.emitWarning("i has reached 3");
  }
}, 1000);

process.on('warning', function(){
  console.log("warning received");
});


As you can see when i becomes 3,  a warning is emitted which prints (node:22536)Warning: i has reached 3. After this our listener is called which prints warning received. The (node:22536) before the message makes the message stand out from your other logs. The number 22536 is the process id which the OS assigns the NodeJS process. It will be different every time you run this.

uncaughtException
      This event is emitted whenever a function throws an error but is not catched using try-catch block. This is a very powerful event as you can prevent your app from crashing even if an error has occurred. This event allows you to perform some custom function with the error like logging it or sending it to developer team etc. If you catch an error, then this event is not emitted.


"use strict";

var validString = `{"website": "compiletimeerror.com"}`;
var invalidString = `{"website" =  "compiletimeerror.com"}`;

var validJSON = JSON.parse(validString);
var invalidJSON = JSON.parse(invalidString);

process.on('uncaughtException', function(err){
  console.log(err);
});


As you can see, since the invalidString is an invalid JSON object, when you try to parse it into JSON NodeJS throws an error. Since we are not catching this error, it shows up in uncaughtException. Also on uncaught error, the process crashes. Since in a server, we do not want our server to crash on error, we can write the code to restart our server within this uncaughtException event handler.

Now see the same thing with try catch.


"use strict";

var validString = `{"website": "compiletimeerror.com"}`;
var invalidString = `{"website" =  "compiletimeerror.com"}`;

try{
var validJSON = JSON.parse(validString);
var invalidJSON = JSON.parse(invalidString);
}catch(err){
  console.log("Some error");
}

process.on('uncaughtException', function(err){
  console.log(err);
});

In this example we surround the parsing functions within a try catch block. Whenever some error occurs, the try catch block catches it and it prevents server from crashing. In such cases, since the exception or error is handled, the uncaughtException event is not triggered.


As you can see the catch block executes our code and prints “Some Error” instead of the error message.

These are the frequently used process events in NodeJS. There are others also but are less frequently used. You can find more information about them in the official documentation of NodeJS.


No comments:
Write comments

Popular Posts