Process Object in Node Js
- Get link
- X
- Other Apps
Process Object in Node Js
In Node.js, the process object provides information about the current Node.js process and the environment in which it is running. The process object is a global object, which means you can access it from any part of your Node.js application.
Here are some of the commonly used properties and methods of the process object:
Properties
process.argv: An array that contains the command-line arguments passed to the Node.js process.process.env: An object that contains the environment variables of the process.process.pid: The process ID of the Node.js process.process.platform: The platform on which the Node.js process is running (e.g.,'win32'for Windows or'linux'for Linux).process.cwd(): Returns the current working directory of the process.process.exitCode: The exit code that will be used when the process exits.
Methods
process.exit([code]): Exits the Node.js process with an optional exit code.process.on(event, listener): Registers a listener function to be called when a specific event occurs.process.stdout.write(data): Writes data to the standard output stream.process.stderr.write(data): Writes data to the standard error stream.
Here's an example of how to use the process object in a Node.js application:
// Get the command-line arguments const args = process.argv.slice(2); // Get the environment variable const apiKey = process.env.API_KEY; // Get the process ID const pid = process.pid; // Register an event listener for the 'exit' event process.on('exit', (code) => { console.log(`Process exited with code ${code}`); }); // Write to the standard output stream process.stdout.write('Hello, world!\n'); // Exit the process with an exit code process.exit(0);
process.argv to get the command-line arguments passed to the process, process.env to get an environment variable, process.pid to get the process ID, and process.on to register an event listener for the exit event. We're also using process.stdout.write to write to the standard output stream and process.exit to exit the process with an exit code.- Get link
- X
- Other Apps
Comments