Whenever you run a Node.js application, a special object called process is automatically available.
This object provides information about the currently running Node.js process and allows you to interact with it.
Whether you're reading environment variables, accessing command-line arguments, or handling application shutdown events, you'll frequently use the Process module in real-world Node.js applications.
In this article, we'll learn:
- What the Process module is
- What
process.envis - What
process.argvis - What
process.on()is - Real-world examples
- Best practices
Let's get started!
What is the Process Module?
The Process module is a built-in global object in Node.js that provides information and control over the currently running process.
The best part is:
You don't need to install or import it.
Unlike Express or other packages, process is available globally.
Simply write:
console.log(process);
and you'll see a large object containing useful information about your application.
What Can We Do with the Process Module?
The process object provides many useful properties and methods, such as:
- Read environment variables
- Read command-line arguments
- Handle application exit events
- Get the current working directory
- Exit the application
- Check memory usage
- Get Node.js version
- Handle uncaught exceptions
Some commonly used properties include:
process.env
process.argv
process.cwd()
process.exit()
process.version
process.memoryUsage()
process.on()
In this article, we'll focus on the three most commonly used ones:
process.envprocess.argvprocess.on()
Understanding process.env
What is process.env?
process.env is an object that contains all the environment variables available to your Node.js application.
Environment variables are values stored outside your code that can be used to configure your application.
Examples include:
- Database URL
- API Keys
- Secret Keys
- Port Number
- Environment (Development or Production)
Instead of writing these values directly inside your code, we store them in environment variables.
This makes applications:
- More secure
- Easier to configure
- Easier to deploy
Step 1: Print All Environment Variables
Create a file called:
env.js
Add the following code:
console.log(process.env);
Run the file:
node env.js
You'll see a large object containing environment variables from your operating system.
Example:
{
PATH: "...",
HOME: "/Users/john",
USER: "john",
SHELL: "/bin/zsh"
}
The exact output depends on your operating system.
Step 2: Read a Specific Environment Variable
Instead of printing everything, we can access a specific variable.
console.log(process.env.PATH);
Run:
node env.js
Output:
C:\Program Files\nodejs;...
or
/usr/local/bin:...
depending on your operating system.
Using Custom Environment Variables
Suppose you want your application to run on a configurable port.
Instead of writing:
const PORT = 3000;
You can write:
const PORT = process.env.PORT || 3000;
console.log(PORT);
Now run:
Windows (Command Prompt)
set PORT=5000
node env.js
Windows (PowerShell)
$env:PORT=5000
node env.js
macOS/Linux
PORT=5000 node env.js
Output:
5000
If PORT isn't defined, the application will use the default value of 3000.
Real-World Example of process.env
Imagine you're connecting to a database.
Instead of doing this:
const dbPassword = "mySecretPassword";
Use:
const dbPassword = process.env.DB_PASSWORD;
This keeps sensitive information outside your source code.
In production applications, developers usually store these values in a .env file and load them using packages like dotenv.
Understanding process.argv
What is process.argv?
process.argv is an array that contains the command-line arguments passed to your Node.js application.
This is extremely useful for:
- CLI tools
- Scripts
- Automation
- Utility programs
Step 1: Print process.argv
Create:
argv.js
Add:
console.log(process.argv);
Run:
node argv.js
Example output:
[
'/usr/local/bin/node',
'/Users/john/Desktop/argv.js'
]
The array always contains:
- Index 0 → Node.js executable path
- Index 1 → Current file path
Step 2: Pass Custom Arguments
Run:
node argv.js John 25 India
Output:
[
'/usr/local/bin/node',
'/Users/john/Desktop/argv.js',
'John',
'25',
'India'
]
Access Individual Arguments
console.log(process.argv[2]);
console.log(process.argv[3]);
console.log(process.argv[4]);
Output:
John
25
India
Step 3: Build a Greeting Application
const name = process.argv[2];
console.log(`Hello ${name}!`);
Run:
node argv.js Sundar
Output:
Hello Sundar!
Another Example
const firstNumber = Number(process.argv[2]);
const secondNumber = Number(process.argv[3]);
console.log(firstNumber + secondNumber);
Run:
node argv.js 20 30
Output:
50
Congratulations!
You've just created your first command-line calculator.
Real-World Uses of process.argv
Many popular tools use command-line arguments.
For example:
npm install express
git commit -m "Initial Commit"
node server.js production
These commands internally read arguments using logic similar to process.argv.
Understanding process.on()
What is process.on()?
process.on() is used to listen for events that occur during the lifetime of a Node.js process.
Think of it as adding event listeners to your application.
Syntax:
process.on(eventName, callback);
Whenever the specified event occurs, the callback function is executed.
Common Events
Some commonly used events include:
exit
beforeExit
SIGINT
uncaughtException
unhandledRejection
warning
Let's understand the most useful ones.
Example 1: exit Event
Create:
exit.js
Add:
process.on("exit", () => {
console.log("Application is exiting...");
});
console.log("Program Running...");
Run:
node exit.js
Output:
Program Running...
Application is exiting...
The exit event is triggered just before the Node.js process terminates.
Example 2: SIGINT Event (Ctrl + C)
process.on("SIGINT", () => {
console.log("\nServer stopped successfully.");
process.exit();
});
Run:
node exit.js
Now press:
Ctrl + C
Output:
Server stopped successfully.
This is commonly used in Express applications to gracefully stop the server.
Example 3: uncaughtException
process.on("uncaughtException", (error) => {
console.log("Unexpected Error:");
console.log(error.message);
});
throw new Error("Something went wrong!");
Output:
Unexpected Error:
Something went wrong!
Instead of crashing immediately, you can log the error or perform cleanup before exiting. In production, it's generally recommended to log the error and then terminate the process, because the application may be in an inconsistent state.
Example 4: unhandledRejection
Suppose someone forgets to handle a rejected Promise.
process.on("unhandledRejection", (error) => {
console.log(error);
});
Promise.reject("Database Connection Failed");
Output:
Database Connection Failed
This helps identify Promise rejections that weren't handled with .catch() or try...catch in async functions.
Real-World Example
Imagine you're running an Express server.
When you press Ctrl + C, you don't want to stop the server abruptly.
Instead, you can close database connections, stop background jobs, and release resources before exiting.
process.on("SIGINT", () => {
console.log("Closing Database...");
console.log("Stopping Server...");
process.exit();
});
This is called graceful shutdown, and it's an important practice for production applications.
Best Practices
When working with the Process module:
- Never hardcode secrets inside your source code.
- Use
process.envfor configuration values. - Validate command-line arguments before using them.
- Handle
SIGINTto shut down your application gracefully. - Log unexpected errors using
uncaughtExceptionandunhandledRejection, then exit the process if necessary. - Keep environment-specific values outside your codebase.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Hardcoding API keys instead of using environment variables.
- Assuming command-line arguments always exist without validation.
- Forgetting that
process.argv[0]andprocess.argv[1]are reserved for the Node executable and script path. - Ignoring unhandled Promise rejections.
- Forcefully terminating applications without cleanup.
Final Thoughts
The process module is one of the most important built-in features of Node.js. Although it may seem simple at first, it's used extensively in production applications for configuration, command-line tools, graceful shutdowns, and error handling.
In this article, you learned:
- What the
processobject is - How to use
process.envto manage configuration - How to use
process.argvto read command-line arguments - How to use
process.on()to respond to application lifecycle events - Practical examples and best practices
As you continue your Node.js journey, you'll encounter the process object in almost every backend project. Understanding it early will make building and maintaining Node.js applications much easier.
Happy Coding! 🚀