The process
module in Node.js provides information and control over the process in which our application runs.
From obtaining command line arguments, handling events, to controlling the application’s execution.
Examples of using the Process module
Getting command line arguments
We can use the process
object to access the arguments passed to the application from the command line.
import process from 'node:process';
const args = process.argv.slice(2);
console.log('Command line arguments:', args);
Getting the current working directory
We can also use the process
object to get the current working directory of our application.
import process from 'node:process';
const cwd = process.cwd();
console.log('Current working directory:', cwd);
Exiting the process with an exit code
The process
object allows us to control the termination of the process and specify an exit code.
import process from 'node:process';
// Exit with exit code 0 (success)
process.exit(0);
// Exit with exit code 1 (error)
process.exit(1);
Getting information about the process environment
We can use the process
object to get information about the environment in which our application runs, such as the process ID, Node.js version, platform, architecture, and environment variables.
import process from 'node:process';
console.log('Process ID:', process.pid);
console.log('Node.js version:', process.version);
console.log('Platform:', process.platform);
console.log('Architecture:', process.arch);
console.log('Environment variables:', process.env);
Listening to process events
The process
object allows us to listen to events related to the process, such as process termination, uncaught exceptions, and system signals.
import process from 'node:process';
process.on('exit', (code) => {
console.log(`Process terminated with exit code: ${code}`);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
});
process.on('SIGINT', () => {
console.log('Received SIGINT signal (Ctrl+C)');
process.exit(0);
});
Changing the process window title
We can use the process
object to change the process window title.
import process from 'node:process';
process.title = 'My Application';
console.log('Process title:', process.title);
Spawning a process
The process
module also allows us to spawn child processes using the ‘spawn’ method from the ‘child_process’ module.
import { spawn } from 'node:child_process';
// Command to open gedit in Linux or macOS
const command = 'gedit';
// Optional arguments, in this case not necessary
const args = [];
const process = spawn(command, args);
process.on('error', (err) => {
console.error('Error starting the process:', err);
});
process.on('exit', (code) => {
console.log(`Process finished with exit code: ${code}`);
});