- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js Process
The process object is one of the most fundamental tools in a Node.js developer's toolkit. It is a global object meaning you don't need to use require() or import to use it that acts as a bridge between your JavaScript code and the operating system. It provides essential information about the current running instance of your application and allows you to control how that application behaves within the system environment.
process is global, you can access it anywhere in your project, but be careful not to overwrite it with your own variables!
Key Features of Process
- Access to Command-Line Arguments: Use
process.argvto create interactive CLI (Command Line Interface) tools by capturing input from the user at startup. - Environment Variables: Use
process.envto manage configuration settings, such as database credentials or API keys, without hardcoding them into your source code. - Exit Control: Use
process.exit()to programmatically shut down your application when a task is finished or a fatal error occurs. - Process State: Retrieve vital statistics like memory usage, the process ID (PID), and the current directory to help with debugging and logging.
Common Process Methods and Properties
1. process.argv
The argv (argument vector) property returns an array containing the command-line arguments passed when the Node.js process was launched. Understanding the structure of this array is crucial because the first two elements are always occupied by Node.js itself.
// Run this as: node script.js dev-mode --port=3000
console.log(process.argv);
Output:
[
'/usr/local/bin/node', // Path to the Node executable
'/path/to/script.js', // Path to your JavaScript file
'dev-mode', // First custom argument
'--port=3000' // Second custom argument
]
- The real data you care about usually starts at index
2.
process.argv[0]. Remember that process.argv[0] is always the path to the Node engine, and process.argv[1] is the script file path.
2. process.env
The env property is an object that mirrors your operating system's environment variables. This is the industry-standard way to handle "secrets" and environment-specific logic (like switching between a local test database and a production database).
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
console.log(`Server will run on port: ${port}`);
Output:
Server will run on port: 3000
.env file and use the process.env object to load them into your application securely.
3. process.exit()
The exit() method forces the process to terminate. It accepts a "status code" as an integer. A code of 0 tells the OS that the script finished successfully, while any non-zero code (like 1) signals that something went wrong.
if (!process.env.API_KEY) {
console.error('Missing API_KEY! Exiting...');
process.exit(1); // Exit with failure
}
console.log('App started successfully.');
process.exit() will stop everything immediately, even if there are still pending asynchronous operations (like a database write). Use it sparingly in production code.
4. process.pid
The pid property (Process ID) is a unique number assigned by the operating system to this specific running instance of your app. This is very useful for logging and for tools that monitor process health.
console.log(`Process ID: ${process.pid}`);
- If your app crashes or hangs, you can use this ID in your system terminal (e.g.,
kill -9 12345) to manually stop it.
5. process.uptime()
This method returns a floating-point number representing the number of seconds the current Node.js process has been running. It is a simple way to track how long your server has been "up."
const uptime = process.uptime();
console.log(`The server has been running for ${uptime.toFixed(2)} seconds.`);
process.uptime() to create a "health check" endpoint in your web API, allowing monitoring tools to verify that your service is still responsive.
6. process.cwd()
The cwd() (Current Working Directory) method tells you where the user was standing in their file system when they started the Node process. This is different from __dirname, which always points to the location of the file itself.
console.log(`The process was started from: ${process.cwd()}`);
process.cwd(), your script might fail to find files if you run it from a different folder than you expected.
7. process.memoryUsage()
This returns an object that provides a snapshot of how much RAM your application is consuming. This is vital for detecting "memory leaks" in long-running applications.
const memory = process.memoryUsage();
console.log(`Heap Used: ${(memory.heapUsed / 1024 / 1024).toFixed(2)} MB`);
Output:
{
rss: 12487680, // Total memory allocated for the process
heapTotal: 5201920, // Total size of the allocated heap
heapUsed: 3153568, // Memory actually used by your objects/variables
external: 4502 // Memory used by C++ objects bound to JavaScript
}
heapUsed regularly. If this number keeps growing indefinitely without ever going down, your application likely has a memory leak that will eventually cause a crash.
Summary
The process object is the ultimate control center for any Node.js application. By mastering process.argv and process.env, you can build flexible, configurable scripts. By monitoring process.pid, uptime(), and memoryUsage(), you gain the visibility needed to maintain professional-grade software. Whether you are building a simple automation script or a high-traffic web server, the process object is your primary interface for interacting with the system environment.