Backend
Node.js
Global Objects and Variables

Global Objects and Variables in Node.js

When transitioning from Frontend JavaScript (the browser) to Backend JavaScript (Node.js), one of the first conceptual shifts involves understanding the global execution context. In Node.js, several objects and functions are available anywhere in your application without needing to require or import them.

Here is the complete, categorized breakdown of Node.js Globals.


1. Module-Related Globals (Pseudo-Globals)

In Node.js, every file is treated as an isolated Module. Node.js invisibly wraps your code in a function before executing it. Because of this, the following variables appear to be global, but are actually just arguments scoped to the current file.

  • require: Function used to import CommonJS modules.
  • module: An object representing the current module you are writing in.
  • exports: A shortcut reference to module.exports.
  • __dirname: The absolute path to the directory containing the current file.
  • __filename: The absolute path to the current file itself.

Example:

const fs = require('fs');
 
console.log(__dirname);  // e.g., /Users/pratapdas/Developer/project/src
console.log(__filename); // e.g., /Users/pratapdas/Developer/project/src/app.js

[!WARNING] If you use ES Modules (import / export), these 5 variables are not available.


2. Process Globals

The process object is the single most important global in backend engineering. It provides deep information about, and control over, the active Node.js OS process.

  • process.env: Used to access secure environment variables (e.g., Database passwords).
  • process.argv: An array of command-line arguments passed when launching the Node process.
  • process.cwd(): Returns the current working directory of the Node.js process.
  • process.exit(): Forcefully terminates the Node.js server.
  • process.pid: Returns the Process ID (PID) assigned by the Operating System.

Example:

console.log(process.env.NODE_ENV); // "production" or "development"

3. The Global Object

In Node.js, the absolute top-level object is called global (unlike the browser, which uses window).

  • global: The Node.js specific global object.
  • globalThis: A modern JavaScript standard that universally points to the global object regardless of the environment (works in both Browser and Node.js).

Example:

global.appName = "MyApp";
console.log(global.appName);

[!CAUTION] Anti-Pattern: Attaching variables directly to the global object is heavily discouraged in enterprise systems. It leads to namespace collisions, memory leaks, and makes unit testing extremely difficult.


4. Timers

Node.js provides standard global timers to schedule code execution.

  • setTimeout(): Executes code once after a minimum delay.
  • setInterval(): Executes code repeatedly at specified intervals.
  • setImmediate(): (Node.js specific) Executes a callback on the next iteration of the Event Loop. Crucial for breaking up heavy CPU tasks so you don't block the server.
  • clearTimeout(), clearInterval(), clearImmediate(): Used to stop the respective timers.

5. Buffer

Because backend servers constantly interact with the filesystem and TCP network streams, Node.js includes the Buffer global to handle raw binary data directly in memory.

Example:

const buf = Buffer.from('hello');
console.log(buf); // Prints hexadecimal representation: <Buffer 68 65 6c 6c 6f>

6. Web APIs Available in Modern Node.js (18+)

Historically, you had to install external packages like axios to make HTTP requests or uuid for cryptography. Modern Node.js now includes many standard Web APIs globally:

  • fetch: For making HTTP requests.
  • URL / URLSearchParams: For parsing and formatting URLs.
  • AbortController / AbortSignal: For cancelling ongoing fetch requests.
  • TextEncoder / TextDecoder: For converting between strings and binary data.
  • crypto: Web Crypto API for hashing and encryption.
  • performance: For high-resolution performance timing.

Example:

const res = await fetch('https://api.example.com/data');
const data = await res.json();

7. How to Check All Globals Dynamically

If you ever want to see exactly what is available in the global scope at runtime, you can log the keys of the global object:

console.log(Object.keys(global));
// OR
console.log(global);

8. Difference from Browser Globals

The environment you run your JavaScript in dictates what globals are available.

The Browser has:

  • window
  • document (DOM manipulation)
  • localStorage
  • navigator (Browser information)

Node.js does NOT have those by default. Because a server doesn't have a screen or a DOM, it provides backend-specific globals instead:

  • global
  • process
  • Buffer
  • require