The process object is a built-in module in Node.js that provides information about the current Node.js process running on the machine. It allows you to interact with the current process, control its behavior, and customize Node.js applications to meet specific requirements. In this article, you will explore some of the most important methods and properties provided by the process object in Node.js.
Process environment
The process.env object is used to store environment variables that are available to the current Node.js process. Environment variables are key-value pairs that are used to configure various aspects of the operating system and the applications running on it. The process.env object allows developers to access and modify these environment variables. Try to print the process.env to the console like this:
console.log(process.env);In any machine and environment, the result will be different. But you can see the following example of the env object:
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}It is useful when developing applications, but it would be more handy if you store all environment variables in the file of the current environment. To do that, create an .env file in the root directory of your application, then add variables to this file using the environment format. By default, Node.js will not see the .env file and will not be able to add variables from it to the process.env object. You need to install and import the dotenv package, which will allow you to use the .env file:
// .env
MY_ENV_VAR=12
// index.mjs
import * as dotenv from 'dotenv';
dotenv.config();
console.log(process.env);{
...
npm_node_execpath: '/usr/local/bin/node',
npm_config_prefix: '/usr/local',
COLORTERM: 'truecolor',
MY_ENV_VAR: '12'
}So you can see in the result above, that the defined variable is now accessible in the process.env object. You can store secrets as a token or API server address in the .env file, but never store the .env file in the repository or package of the application because your secrets will never be secret anymore. An .env file should always be created in each new environment of the application: a server, your computer, or some other container.
Process arguments
The process.argv object returns an arguments list of the current process. The first item of the argv array is the absolute path of the executable Node.js process, and the second will be the absolute path to the current module that raises the process.
console.log(process.argv);
// $ node index.mjs
// Output:
[
'/usr/local/bin/node',
'/Users/username/hs/process-object/index.mjs'
]To see the passed arguments in argv, you need to pass them first. To do that, write arguments after the filename when running the Node.js process. See the following example:
console.log(process.argv);
// $ node index.js hello args
// Output:
[
'/usr/local/bin/node',
'/Users/username/hs/process-object/index.js',
'hello',
'args'
]As you can see, the passed arguments are hello and args. You can use this feature when you need to create relative logic. This may come in handy if you need the input parameters to affect the execution of your program.
Standard input and output
process.stdin (standard input) and process.stdout (standard output) are streams that allow developers to communicate with the user through the console or terminal window. process.stdin is an input stream, you can use it to listen to events on it, then pass the callback function to do something with the inputted data. On the other hand, the process.stdout stream provides access to the current process terminal or console. process.stdout.write() will write any message in the console, same as console.log().
To better understand it, take a look at the code snippet below. When running a node application, this code prints messages in the console and waits for the user to enter a response. The messages will be displayed differently depending on the arguments (flags) passed in.
// Check for flag and define messages
const isLogin = process.argv.some((arg) => arg === '--login');
const loginMessage = `Welcome back! \b\nEnter your name to come in: `;
const registerMessage = `Welocome on the board! \b\nEnter your name to register: `;
// Ask user to enter the response
process.stdout.write(isLogin ? loginMessage : registerMessage);
// Read the users response
process.stdin.on('data', (input) => {
// Define messages
const enteredName = input.toString().trimEnd();
const loginMessage = `Welocome back, ${enteredName}!`;
const registerMessage =
`Welcome, ${enteredName}!
\b\nYou have successfully registered!
\nUse --login flag to login!`;
// Return the message
process.stdout.write(isLogin ? loginMessage : registerMessage);
});First of all, you need to store the passed flag by process.argv object, then define messages that the user will see when the app will start. Write messages depending on the passed flag, then listen to the user's input and write a new message depending on the flag that was used at the start.
If you try to run this code, you will see a classic example of user interaction with a program through the console. This is the same for example when you initialize an npm package. However, here you will need to stop the program with CTRL+C combination. As that isn't very comfortable, to properly stop the program, you could use the process.exit() function.
Process exit
When you interact with the user through the console, you will need to stop the program. To do that, you can use the process.exit() function. It will terminate the current process.
const isLogin = process.argv.some((arg) => arg === '--login');
const loginMessage = `Welcome back! \b\nEnter your name to come in: `;
const registerMessage = `Welocome on the board! \b\nEnter your name to register: `;
process.stdout.write(isLogin ? loginMessage : registerMessage);
process.stdin.on('data', (input) => {
const enteredName = input.toString().trimEnd();
const loginMessage = `Welocome back, ${enteredName}!`;
const registerMessage =
`Welcome, ${enteredName}!
\b\nYou have successfully registered!
\nUse --login flag to login!`;
process.stdout.write(isLogin ? loginMessage : registerMessage);
// Terminate the process
process.exit();
});The process.exit() takes one argument, exit code. It will be 0 or 1, where 0 is the regular end of the program, but 1 is an error.
The exit code passed to the process.exit() method can be used to pass information about the success or failure of a Node.js process to other processes or systems. For example, some tools or services may expect a particular exit code from the Node.js process to determine whether it was successful.
It is essential to use the process.exit() method with caution, as this can result in the loss of unsaved data. In general, it is recommended to gracefully terminate the Node.js process by allowing it to complete all pending tasks before exiting.
Conclusion
The process object in Node.js provides a wide range of methods and properties to interact with any current running Node.js process. The set of functions and process objects makes it possible to create simple console applications, using function calls to the console and waiting for user input in order to control the program. Environment variables allow you to execute the program with different inputs, depending on the environment. This is most often used by developers to separate the server and local environments, and depending on the environment variables, make requests to different resources, or run the application in different modes.
Overall, the process object is a good tool that can greatly enhance the functionality and usability of Node.js applications.