Skip to content

Node.js Global Objects

Node.js provides certain objects and functions that are available in all modules without needing to explicitly require them. These are known as global objects or globals. While convenient, excessive use of globals can make code harder to maintain and understand.

In browsers, the global scope object is window. In Node.js, it’s global. To write cross-platform code (Node.js and browsers), the standard globalThis property can be used, which refers to the correct global object in either environment.

Any variable declared outside a function (and not using const or let in the module’s top level) technically becomes a property of the global object, though this practice is strongly discouraged in modern JavaScript.

// Example (Avoid doing this in real code!)
global.myGlobalVar = 'I am global';
console.log(myGlobalVar); // Accessible directly
console.log(globalThis.myGlobalVar); // Also accessible via globalThis

Some globals are specific to the current module context:

A string representing the absolute path to the currently executing file.

// In a file named /path/to/your/app/main.js
console.log(__filename);

Output:

/path/to/your/app/main.js

A string representing the absolute path to the directory containing the currently executing file.

// In a file named /path/to/your/app/main.js
console.log(__dirname);

Output:

/path/to/your/app

These are particularly useful for constructing paths relative to the current file, e.g., when reading adjacent configuration files or serving static assets.

The function used to import modules in the CommonJS module system. While it feels like a global, it’s actually specific to each module.

An object representing the current module, often used for exporting functionality via module.exports.

A reference to module.exports, providing a shorthand for exporting.

Node.js provides timer functions similar to those found in web browsers, allowing you to schedule code execution.

Schedules the execution of the callback function once after the specified delay (in milliseconds). Additional args will be passed to the callback function.

It returns a Timeout object, which can be used with clearTimeout to cancel the scheduled execution.

Example:
function greet(name) {
console.log(`Hello, ${name}! This message is delayed.`);
}
console.log('Scheduling greeting...');
const timeoutId = setTimeout(greet, 2000, 'Node Developer'); // Execute after 2 seconds
console.log('Greeting scheduled. Timeout ID:', timeoutId);
// To potentially cancel it later:
// clearTimeout(timeoutId);

Cancels a Timeout object previously created by setTimeout.

Example:
function neverCalled() {
console.log('This should not appear.');
}
const doomedTimeout = setTimeout(neverCalled, 1500);
console.log('Timeout scheduled, but will be cleared immediately.');
clearTimeout(doomedTimeout);
console.log('Timeout cleared.');

Schedules the repeated execution of the callback function every delay milliseconds. Additional args are passed to the callback on each execution.

It returns an Interval object, which can be used with clearInterval to stop the repeated executions.

Example:
let counter = 0;
function tick() {
counter++;
console.log(`Tick number: ${counter}`);
if (counter >= 5) {
console.log('Stopping interval.');
clearInterval(intervalId);
}
}
console.log('Starting interval...');
const intervalId = setInterval(tick, 1000); // Execute every 1 second
console.log('Interval started. Interval ID:', intervalId);

Cancels an Interval object previously created by setInterval.

setImmediate(callback[, …args]) and clearImmediate(immediateId)

Section titled “setImmediate(callback[, …args]) and clearImmediate(immediateId)”

setImmediate schedules the callback to execute in the next iteration of the event loop, specifically during the ‘check’ phase, which runs after I/O callbacks. It’s often used to break up long-running synchronous operations to allow the event loop to process I/O.

While not functions you call directly like timers, these are crucial global objects:

S.N.Global NameDescription
1ConsoleUsed for printing messages to standard output (stdout) and standard error (stderr). Provides methods like console.log(), console.error(), console.warn(), console.table(), console.time(), console.timeEnd(), etc.
2ProcessAn object providing information about, and control over, the current Node.js process. Key properties and methods include:
process.argv: Array of command-line arguments.
process.env: Object containing environment variables.
process.cwd(): Current working directory.
process.exit([code]): Exits the process.
process.on('event', callback): Listen for process-related events (e.g., ‘uncaughtException’, ‘exit’, ‘SIGINT’).
process.stdout, process.stdin, process.stderr: Standard I/O streams.
3BufferUsed for handling binary data directly. Essential for working with TCP streams, file system operations, etc. We will cover Buffers in a later chapter.

Note: While many functions and objects are globally accessible, it’s generally good practice to explicitly require modules when needed (except for the truly fundamental globals like console, process, timers, __filename, __dirname) to make code dependencies clearer.