In node.js, process object is a global object and it is useful to provide the information about the current or active node.js process. In node.js, process is a global object so we can use the process object in node.js applications without using require() directive.
In node.js, process object is an instance of EventEmitter object and it will emit or trigger events based on the behavior.
The following table lists the different types of process events available for process objects in node.js.
Event | Description |
---|---|
beforeExit | This event will be triggered whenever the event loop is empty and there is no additional work to schedule. |
disconnect | This event will be emitted when the IPC channel is closed. |
exit | This event will be emitted when the node.js process is about to exit. |
message | This event will be triggered whenever the message sent by a parent process is received by the child process. |
uncaughtException | This event will be emitted whenever an uncaught exception occurred. |
unhandleRejection | This event will be emitted whenever a promise is rejected and no error handler is attached to the promise within a turn of the event loop. |
For example, to understand process events, let’s create a new file called processevents.js and write the following lines of code to listen for an exit event.
process.on('exit', (code) => {
console.log("Inside Exit Event");
// this will not run
setTimeout(() => {
console.log('This will not run');
}, 0);
console.log('Exit with code :', code);
});
console.log("Program End");
Generally, the node.js process will exit immediately after calling ‘exit’ event listeners so any work queued in the event loop will be abandoned. In above example, the setTimeout function will never execute.
When we execute the above code in node.js command prompt, we will get the result like as shown below.
If you observe the above result, the setTimeout function not executed and completely ignored by the process after calling the exit event listener.
If you observe the above example result, the node.js process exit with code 0. Generally, the node.js will exit with a 0 status when no more async operations are pending. The following are the different status exit codes that will occur in other cases.
Code | Description |
---|---|
1 (Uncaught Fatal Exception) | We will get this exit code when there was an uncaught exception. |
2 (Unused) | This exit code is reserved by bash for builtin misuse. |
3 (Internal JavaScript Parse Error) | This exit code will occur only when the internal javascript source code of node.js caused a parse error. It's very rare and can only happen during node.js development. |
4 (Internal JavaScript Evaluation Failure) | This exit code will occur only when the internal javascript source code of node.js failed to return function value. It's very rare and can only happen during node.js development. |
5 (Fatal Error) | We will get this exit code only when there was a fatal unrecoverable error. |
6 (Non-function Internal Exception Handler) | This exit code will occur when an internal exception handler somehow set to non-function to handle the uncaught exception. |
7 (Internal Exception Handler Run-Time Failure) | This exit code will occur when an internal fatal exception function itself throw an error while attempting to handle the uncaught exception. |
8 (Unused) | In previous versions of Node.js, exit code 8 sometimes indicated an uncaught exception. |
9 (Invalid Argument) | This exit code will occur when an unknown option is specified or an option requiring a value was provided without a value. |
10 (Internal JavaScript Run-Time Failure) | This exit code will occur only when the internal javascript source code of node.js throws an error when the bootstrapping function was called. It's very rare and can only happen during node.js development. |
12 (Invalid Debug Argument) | This exit code will occur only when --inspect or --inspect-brk options were set but the choosen port numbers are invalid or unavailable. |
In node.js, the process object is having a different methods to control the system over the interactions.
The following are some of the commonly used process module methods in node.js.
Method | Description |
---|---|
abort() | This method is useful to abort the currently active process, and at last, it generates core files. |
cwd() | This method is useful to return the current working directory of the node.js process. |
chdir() | This method is useful to change the current working directory of the node.js process. |
uptime() | This method will return the number of seconds the current Node.js process has been running. |
exit() | This method will instruct the node.js to terminate the current process. |
getgid() | This method will return the numerical group identity of the process. |
getgroups() | This method will return an array with the supplementary group IDs. |
setgid() | This method is useful to set the group identity of the process. |
setuid() | This method will set the user identity of the process. |
kill() | The method is used to kill the process by providing the processid and signal. |
memoryUsage() | This method will return an object which describes the memory usage of the Node.js process measured in bytes. |
For example, to understand process methods, let’s create a new file called processmethods.js and write the following lines of code to get the required values using process methods.
// Provides uptime for the process
console.log("Uptime :", process.uptime());
// Returns the total cpu usage per process
console.log("CPU Usage :", process.cpuUsage());
// Provides the path of current working directory
console.log("Current working directory :", process.cwd());
// To change current working directory
process.chdir("/test");
console.log("New Directory :", process.cwd());
// Returns the configuration about compilation of current file
console.log("Memory Usage :", process.memoryUsage());
If you observe the above example, we are getting the required values of current node.js process and changing the current working directory to another directory.
When we execute the above code in node.js command prompt, we will get the result like as shown below.
If you observe the above result, we got the required details of the current node.js process using process methods based on our requirements.
Same as process methods & events, the node.js process is having a property to control the system over the interactions.
The following are some of the important process module properties in node.js.
Property | Description |
---|---|
pid | This property will return the PID of the process. |
title | This property will return the current process title. |
version | This property will return the current node.js version. |
platform | This property will return a string by identifying the operating system platform on which the Node.js process is running. |
config | This property will return the object containing the JavaScript representation of the configure options used to compile the current Node.js executable. |
debugPort | This property is useful to get the port used by node.js debugger. |
env | This property will return an object containing the user environment. |
execPath | This property will return the absolute pathname of the executable that started the node.js process. |
stderr | This property will return a stream that is connected to stderr. |
stdin | This property will return a stream that is connected to stdin. |
stdout | This property will return a stream that is connected to stdout. |
For example, to understand process properties, let’s create a new file called processproperties.js and write the following lines of code to get the required values using process properties.
// pid of process
console.log("Pid: ", process.pid);
// process title
console.log("Title: ", process.title);
// node.js version
console.log("Version: ", process.version);
// os platform
console.log("Platform: ", process.platform);
// node.js exe path
console.log("Path: ", process.execPath);
If you observe the above example, we are getting the required values of current node.js process by using process properties.
When we execute the above code in node.js command prompt, we will get the result like as shown below.
If you observe the above result we got the required details of the current node.js process using process properties based on our requirements.