Difficulty: Beginner
In browser JavaScript, the global object is 'window'. In Node.js, the global object is called 'global' (or the standardized 'globalThis' which works in both environments). Any property attached to the global object is accessible everywhere without imports. However, unlike the browser where variables declared with var at the top level become properties of window, Node.js modules are wrapped in a function scope, so top-level variables are local to that module.
Node.js provides several important global variables and functions. The __dirname variable contains the absolute path of the directory containing the current module file. The __filename variable contains the absolute path of the current module file itself. These are essential when working with file paths because they give you reliable absolute paths regardless of where the Node.js process was started from. Note that __dirname and __filename are only available in CommonJS modules; in ES modules, you need to use import.meta.url instead.
The process object is one of the most important globals in Node.js. It provides information about and control over the current Node.js process. process.env is an object containing the user environment variables, which is how you access configuration like database URLs, API keys, and port numbers. process.argv is an array containing the command-line arguments passed when the Node.js process was launched, where argv[0] is the path to the node executable and argv[1] is the path to the script being run.
Beyond env and argv, the process object offers many useful methods and properties. process.exit(code) terminates the process with the given exit code (0 for success, 1 for failure). process.cwd() returns the current working directory. process.memoryUsage() returns an object showing heap memory consumption. process.uptime() returns the number of seconds the process has been running. process.stdin, process.stdout, and process.stderr are streams for reading input and writing output.
Other global utilities include console (for logging), setTimeout, setInterval, setImmediate (Node-specific), queueMicrotask, Buffer (for binary data), URL and URLSearchParams (for URL parsing), TextEncoder and TextDecoder, and the performance object for high-resolution timing. Starting from Node.js 18, fetch is also available globally for making HTTP requests.
// __dirname: absolute path of the current file's directory
console.log("Directory:", __dirname);
// __filename: absolute path of the current file
console.log("File:", __filename);
// globalThis works in both Node.js and browsers
console.log("globalThis === global:", globalThis === global);
// Variables in modules are NOT global
const secret = "hidden";
console.log("global.secret:", global.secret); // undefined
// But you CAN explicitly attach to global (not recommended)
global.sharedValue = 42;
console.log("global.sharedValue:", global.sharedValue);
__dirname and __filename provide reliable absolute paths. Unlike browser JavaScript, top-level variables in Node.js are scoped to the module, not the global object. You can attach values to global explicitly, but this is considered bad practice as it creates hidden dependencies.
// Access environment variables
console.log("PATH:", process.env.PATH ? "(exists)" : "(not set)");
console.log("NODE_ENV:", process.env.NODE_ENV || "not set");
console.log("HOME:", process.env.HOME || process.env.USERPROFILE);
// Set environment variables at runtime
process.env.MY_APP_PORT = "8080";
process.env.MY_APP_DEBUG = "true";
console.log("Port:", process.env.MY_APP_PORT);
console.log("Debug:", process.env.MY_APP_DEBUG);
// Note: all env values are strings
console.log("Type of port:", typeof process.env.MY_APP_PORT);
// Common pattern: default values
const port = parseInt(process.env.PORT || "3000", 10);
console.log("Server port:", port);
Environment variables are the standard way to configure Node.js applications. All values in process.env are strings, so you must parse numbers and booleans yourself. In production, tools like dotenv or the --env-file flag (Node 20.6+) load variables from .env files.
// Run with: node script.js hello --name=World --verbose
// process.argv is an array:
// [0] = path to node executable
// [1] = path to the script
// [2+] = user-supplied arguments
console.log("Full argv:", process.argv);
console.log("Node path:", process.argv[0]);
console.log("Script path:", process.argv[1]);
console.log("User args:", process.argv.slice(2));
// Simple argument parsing
const args = process.argv.slice(2);
const flags = {};
args.forEach(arg => {
if (arg.startsWith('--')) {
const [key, value] = arg.slice(2).split('=');
flags[key] = value || true;
}
});
console.log("Parsed flags:", flags);
process.argv gives you raw access to command-line arguments. The first two elements are always the node path and script path. For complex CLI tools, use libraries like commander, yargs, or the built-in util.parseArgs (Node 18.3+).
global, __dirname, __filename, process.env, process.argv, globalThis