Despite being defined in a process module, the Node.js process object is a global object. It belongs to the EventEmitter class. Details about the active Node.js process are provided by the process object. The current Node.js process can be managed with the use of several methods and properties connected to this object.
Process Events
The process object is an instance of EventEmitter and emits the following events −
Sr.No. | Event & Description |
---|---|
1 | exit Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all exit listeners have finished running, the process will exit. |
2 | beforeExitThis event is emitted when node empties its event loop and has nothing else to schedule. Normally, the node exits when there is no work scheduled, but a listener for ‘beforeExit’ can make asynchronous calls, and cause the node to continue. |
3 | uncaughtExceptionEmitted when an exception bubbles all the way back to the event loop. If a listener is added for this exception, the default action (which is to print a stack trace and exit) will not occur. |
4 | warningThe ‘warning’ event is emitted whenever Node.js emits a process warning. A process warning is similar to an error in that it describes exceptional conditions that are being brought to the user’s attention. |
5 | Signal EventsEmitted when the processes receives a signal such as SIGINT, SIGHUP, etc. |
Example
In the following code, the beforeExit event of the process object is associated with a callback arrow function. Similarly the exit event calls another callback function. The function on beforeExit runs first, followed by the one on exit event.
Open Compiler
process.on('beforeExit',(code)=>{ console.log('A beforeExit event occured with code: ', code);}); process.on('exit',(code)=>{ console.log('Process exit event with code: ', code);}); console.log('This message is displayed first.');
Output
This message is displayed first. A beforeExit event occured with code: 0 Process exit event with code: 0
Notethat only synchronous operations can be carried out by the listener functions. Any further work that is still queued in the event loop will be abandoned since the Node.js process will terminate instantly after calling the ‘exit’ event listeners. For example, in the case below, the timeout will never happen.
Example
Open Compiler
process.on('exit',function(code){// Following code will never execute.setTimeout(function(){ console.log("This will not run");},0); console.log('About to exit with code:', code);}); console.log("Program Ended");
Output
Program Ended About to exit with code: 0
Process Methods
abort()
The abort() method immediately terminates the current process and then creates a core file.
Example
The following program prints a message to the console after every one second, and terminates the loop after 5 seconds as the abort() function is called.
Open Compiler
constabortfunction=()=>{ console.log('Start...');// It prints the message after every 1 second setInterval((function(){return console.log('Hello World');}),1000);// It calls process.abort() after 5 seconds setTimeout((function(){return process.abort();}),5000);};abortfunction();
Output
Start... Hello World Hello World Hello World Hello World
The termination is followed by a long core file output.
chdir()
This method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified directory does not exist).
cwd()
The process.cwd() method returns the current working directory of the Node.js process.
Example
Open Compiler
console.log(`Starting directory: ${process.cwd()}`);try{ process.chdir('NewNodeApp'); console.log(`New directory: ${process.cwd()}`);}catch(err){ console.error(`chdir: ${err}`);}
Output
Starting directory: D:\nodejs New directory: D:\nodejs\NewNodeApp
If the directory is not found, the output will be as follows −
Starting directory:D:\nodejs chdir: Error:ENOENT: no such file or directory, chdir 'D:\nodejs'->'NewDir'
exit()
This method terminates the current process synchronously with an exit status of code (default is ‘success’ code 0). Node.js will not terminate until all the ‘exit’ event listeners are called.
Example
Open Compiler
console.log('Code running'); process.on('exit',function(code){return console.log(`exiting with the error code : ${code}`);});setTimeout((function(){return process.exit(0);//after 5 sec}),5000);
Output
Code running exiting with the error code : 0
kill()
This method terminates the current process and sends a signal to the process identified by pid.
kill(pid[, signal])
Parameters
pid : A process ID
signal : The signal to send, either as a string or number. Default: ‘SIGTERM’.
Signal names are strings such as ‘SIGINT’ or ‘SIGHUP’.
Example
The following code obtains the pid of the current process. It waits for a long enough duration before it exits normally. In between if you emit SIGINT signal by pressing ctrl-C, the process doesn’t terminate.
Open Compiler
const pid = process.pid; console.log(`Process ID: ${pid}`); process.on('SIGHUP',()=> console.log('Received: SIGHUP')); process.on('SIGINT',()=> console.log('Received: SIGINT'));setTimeout(()=>{},100000);// keep process alive setTimeout((function(){return process.kill(pid,'SIGINT');//after 5 sec}),5000);
The terminal shows the process ID and Received: SIGINT whenever ctrlC is pressed. After another timeout of 5 seconds, the kill() method is called, which terminates the process
Process ID: 1776 Received: SIGINT
memoryUsage()
An object detailing the Node.js process’s memory use, expressed in bytes, is returned by this function.
Example
Open Compiler
console.log(process.memoryUsage());
Output
{ rss: 24768512, heapTotal: 4079616, heapUsed: 3153848, external: 1097184, arrayBuffers: 10519 }
nextTick()
This function postpones a callback function’s execution to the subsequent iteration of the event loop.
nextTick(callback[,...args])
This method is a crucial component of the event loop in the Node.js asynchronous API. Each iteration of an Event Loop is referred to as a tick in Node.js. We utilize process.nextTick() to schedule a callback function to be called in the subsequent iteration of the Event Loop.
Example
Open Compiler
console.log('start'); process.nextTick(()=>{ console.log('nextTick callback executed in next iteration');}); console.log('scheduled');
Output
start scheduled nextTick callback executed in next iteration
Process properties
process.arch
The operating system CPU architecture for which the Node.js binary was compiled.
Possible values are −
- ‘arm’,
- ‘arm64’,
- ‘ia32’,
- ‘loong64’,
- ‘mips’,
- ‘mipsel’,
- ‘ppc’,
- ‘ppc64’,
- ‘riscv64’,
- ‘s390’,
- ‘s390x’,
- ‘x64’
Example
Open Compiler
console.log(`This processor architecture is ${process.arch}`);
Output
This processor architecture is x64
process.argv
An array of the command-line parameters supplied when the Node.js process was started is returned by this property. The script can be run from the command line by passing arguments. The parameters are kept in the process.argv array. The JavaScript file is the first element in the array, followed by the arguments supplied, and the node executable is the 0th element.
Save the following script as hello.js and run it from command line, pass a string argument to it from command line.
const args = process.argv; console.log(args);const name = args[2]; console.log("Hello,", name);
In the terminal, enter
PSD:\nodejs> node hello.js thfullstack
['C:\\nodejs\\node.exe','c:\\nodejs\\a.js','thefullstack']
Hello, thefullstack
process.env
property returns an object containing the environment variables.
Example
Open Compiler
const processEnvKeys = Object.keys(process.env); processEnvKeys.forEach((key)=>{ console.log(`${key}: ${process.env[key]}`);});
Output
SystemDrive: C: SystemRoot: C:\WINDOWS TEMP: C:\Users\mlath\AppData\Local\Temp TMP: C:\Users\mlath\AppData\Local\Temp USERDOMAIN: GNVBGL3 USERDOMAIN_ROAMINGPROFILE: GNVBGL3 USERNAME: mlath USERPROFILE: C:\Users\mlath windir: C:\WINDOWS ZES_ENABLE_SYSMAN: 1 TERM_PROGRAM: vscode TERM_PROGRAM_VERSION: 1.84.2 LANG: en_US.UTF-8 COLORTERM: truecolor VSCODE_INJECTION: 1 VSCODE_NONCE: b8069509-e0f5-4bbd-aac9-fc448279b154
You can also set environment variables from the command line. Assign the values to one or more variables before the node executable name.
USER_ID=101USER_NAME=admin node app.js
Inside the script, the environment variables are available as the properties of the process.env object
process.env.USER_ID;// "101" process.env.USER_NAME;// "admin"
process.pid
property returns the PID of the process.
Example
Open Compiler
const{ pid }=require('node:process'); console.log(`This process is pid ${pid}`);
Output
This process is pid 16312
process.platform
This property returns a string identifying the operating system.
The possible values are −
- ‘aix’
- ‘darwin’
- ‘freebsd’
- ‘linux’
- ‘openbsd’
- ‘sunos’
- ‘win32’
process.version
This property contains the Node.js version string.
Example
Open Compiler
console.log(`Version: ${process.version}`);
Output
Version: v20.9.0