The process object in Node.js is a global object, although it is defined in process module. It is an instance of EventEmitter class. The process object provides information on current Node.js process. With the help of a number of methods and properties associated with this object, it is possible to control the current Node.js process.
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 |
beforeExit This 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 |
uncaughtException Emitted 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 |
warning The ”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 Events Emitted 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.
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
Note that the listener functions must only perform synchronous operations. The Node.js process will exit immediately after calling the ”exit” event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur −
Example
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.
const abortfunction = () => { 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
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:nodejsNewNodeApp
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
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.
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()
This function returns an object describing the memory usage of the Node.js process measured in bytes.
Example
console.log(process.memoryUsage());
Output
{ rss: 24768512, heapTotal: 4079616, heapUsed: 3153848, external: 1097184, arrayBuffers: 10519 }
nextTick()
This function defers the execution of a callback function until the next Event Loop Iteration.
nextTick(callback[, ...args])
This function is an important part of the event loop in asynchronous API of Node.js. In Node.js, each iteration of an Event Loop is called a tick. To schedule a callback function to be invoked in the next iteration of the Event Loop, we use process.nextTick().
Example
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
console.log(`This processor architecture is ${process.arch}`);
Output
This processor architecture is x64
process.argv
This property returns an array containing the command-line arguments passed when the Node.js process was launched. You can pass arguments to the script to be executed from the command line. The arguments are stored in a an array process.argv. The 0th element in the array is the node executable, first element is the JavaScript file, followed by the arguments passed.
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
PS D:nodejs> node hello.js TutorialsPoint [ ''C:\nodejs\node.exe'', ''c:\nodejs\a.js'', ''TutorialsPoint'' ] Hello, TutorialsPoint
process.env
property returns an object containing the environment variables.
Example
const processEnvKeys = Object.keys(process.env); processEnvKeys.forEach((key) => { console.log(`${key}: ${process.env[key]}`); });
Output
SystemDrive: C: SystemRoot: C:WINDOWS TEMP: C:UsersmlathAppDataLocalTemp TMP: C:UsersmlathAppDataLocalTemp USERDOMAIN: GNVBGL3 USERDOMAIN_ROAMINGPROFILE: GNVBGL3 USERNAME: mlath USERPROFILE: C:Usersmlath 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=101 USER_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
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
console.log(`Version: ${process.version}`);
Output
Version: v20.9.0