process & Globals
Overview
Node.js provides a set of global variables that are available in every single file by default; you do not need to require them. The most important of these is the process object. It acts as the ultimate bridge between your JavaScript code and the physical Operating System running the Node instance. It allows you to read command-line arguments, check memory usage, listen for termination signals, or forcefully crash the server.
Syntax
// --- 1. The Global Object ---
// In the browser, the global object is 'window'.
// In Node.js, the global object is 'global'.
global.myCustomVar = "Hello";
// --- 2. The Process Object ---
// Reading Command Line Arguments
// If you run: $ node app.js --port 8080
console.log(process.argv);
// Returns an array: ['/path/to/node', '/path/to/app.js', '--port', '8080']
// Forcefully killing the Node application
if (fatalErrorOccurred) {
// 0 means "Success", 1 means "Crashed with an error"
process.exit(1);
}
// Inspecting memory usage (Useful for finding memory leaks!)
console.log(process.memoryUsage());Common Pitfalls
- Attaching variables to
globalinstead of exporting them. If you defineglobal.db = connection, every single file in your massive app can silently mutate the database connection. This causes horrific, untraceable bugs. Always use ES Modules (export/import) to share variables safely. - Misunderstanding
process.argv. Beginners often assume the first item in the array is their argument. It is not. Index 0 is the physical path to the C++ Node executable. Index 1 is the physical path to your JS file. Your actual arguments start at Index 2.
Interview Questions
__dirname and process.cwd()?__dirname is the absolute path to the physical folder where the current JavaScript file lives. process.cwd() is the absolute path to the folder from which the user actually executed the 'node' command in their terminal. They are often different!
Real-World Example
Intercepting a fatal termination signal (like pressing Ctrl+C or a Docker shutdown command) to safely close database connections before the server physically dies.
// Listen for the OS asking Node to shut down (SIGINT = Signal Interrupt)
process.on('SIGINT', async () => {
console.log("Shutting down gracefully...");
await database.disconnect();
console.log("Database disconnected. Goodbye!");
// Now we physically kill the process manually.
process.exit(0);
});Check Your Knowledge
Test your understanding of process & Globals with these quick questions.