Language: EN

obtener-informacion-proceso-nodejs

Obtain process information in Node.js

The process module in Node.js provides information and control over the process in which our application is running.

From obtaining command line arguments, event management, or controlling the execution of the application.

Examples of using the Process module

Get 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);

Get 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);

Exit 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);

Get information about the process environment

We can use the process object to get information about the environment in which our application is running, 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);

Listen to process events

The process object allows us to listen for 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);
});

Change the process window title

We can use the process object to change the title of the process window.

import process from 'node:process';

process.title = 'My Application';
console.log('Process title:', process.title);

Launch a process

The process module also allows us to launch child processes using the ‘spawn’ method from the ‘child_process’ module.

import { spawn } from 'node:child_process';

// Command to open gedit on 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}`);
});

Download the code

All the code from this post is available for download on Github github-full