nodejs
  1. nodejs-process-module

Node.js Process Module

The process module in Node.js is used to interact with the current Node.js process. It provides access to the command-line arguments, environment variables, standard input/output streams, and more.

In this tutorial, we'll discuss how to use the process module in Node.js.

Syntax

The process module can be accessed in Node.js using the process global object. Here's an example of how to access the command-line arguments using the process object:

console.log(process.argv);

Example

Let's say we want to create a Node.js program that takes a command-line argument and prints it to the console. Here's how we can implement it:

// app.js
console.log(`Command-line argument: ${process.argv[2]}`);

Now, we can run the program from the command line:

node app.js hello

This will output:

Command-line argument: hello

Output

When we run the example code above and pass a command-line argument to the program, it will print the argument to the console.

Explanation

In the example above, we created a Node.js program that takes a command-line argument and prints it to the console. We accessed the command-line arguments using the process object's argv property and printed the argument to the console using string interpolation.

Use

The process module in Node.js is commonly used to:

  • Access the command-line arguments and options.
  • Access the environment variables.
  • Terminate the Node.js process.
  • Manage standard input/output streams.
  • Get information about the current Node.js process (e.g. process ID).

Important Points

  • The process.argv array contains the command-line arguments passed to the Node.js program.
  • The process.env object contains the environment variables.
  • Use the process.exit method to terminate the Node.js process with an optional exit code (0 is the default).
  • Use the process.stdin and process.stdout streams to read and write data to the standard input/output.

Summary

In this tutorial, we discussed how to use the process module in Node.js to interact with the current Node.js process. We covered the syntax, example, output, explanation, use, and important points of the process module in Node.js. With this knowledge, you can now use the process module in your Node.js programs to access command-line arguments, environment variables, standard input/output, and more.

Published on: