All academies

Global Objects

process, __dirname, globalThis, timers, and more.

12 minLevel 7 of 20

Globals: available everywhere, no require needed

Some values are available in every Node.js file without importing anything. The browser has window and document; Node has its own set:

  • globalThis — the global object itself (also reachable as global in Node)
  • process — information about and control over the current process
  • console — logging
  • Timers — setTimeout, setInterval, setImmediate and their clear-functions
  • Buffer — binary data (covered in the streams lesson)
  • URL, fetch, structuredClone — modern web-standard APIs, global since Node 18

Remember: variables you declare at a file's top level are module-scoped, not global. To make something truly global you'd assign to globalThis — which is almost always a bad idea in real code.

Meeting the globals
console.log("globalThis is an object:", typeof globalThis === "object");

// Timers are global - no require:
setTimeout(() => console.log("timer fired"), 10);

// Buffer is global too:
const buf = Buffer.from("hi");
console.log("Buffer bytes:", buf.length);

// Top-level variables are NOT global:
const localToThisFile = 42;
console.log("On globalThis?", globalThis.localToThisFile); // undefined

The process object

process is your window into the running program. Its most-used members:

  • process.argv — command-line arguments
  • process.env — environment variables (an object of strings)
  • process.cwd() — the directory the process was started from
  • process.platform and process.version — OS name and Node version
  • process.exitCode / process.exit() — control how the process ends
  • process.memoryUsage() — heap and RSS statistics

process is also an EventEmitter: you can listen for events like exit or uncaughtException (more on those in the error-handling lesson).

Inspecting the process
console.log("Platform:", process.platform);   // e.g. "linux", "darwin"
console.log("Node:", process.version);
console.log("Started from:", process.cwd());

const memory = process.memoryUsage();
console.log("Heap used:",
  Math.round(memory.heapUsed / 1024 / 1024) + " MB");

// env holds environment variables as strings:
console.log("NODE_ENV:", process.env.NODE_ENV ?? "(not set)");

__dirname and __filename

In CommonJS modules, two path variables are injected into every file:

  • __filename — the absolute path of the current file
  • __dirname — the absolute path of the directory containing it

The crucial distinction is __dirname vs process.cwd(). The former is *where the file lives*; the latter is *where the user ran the command*. If a script in /app/src/tool.js is launched from /home/me, then __dirname is /app/src but cwd() is /home/me. For loading files that ship *with your code* (templates, configs), always build paths from __dirname.

Note: ES Modules do not have __dirname; they use import.meta.url (and import.meta.dirname in recent Node versions) instead.

File location vs launch location
const path = require("path");

console.log("This file:", __filename);
console.log("Its folder:", __dirname);
console.log("Launched from:", process.cwd());

// Load a file that ships WITH the code - anchor on __dirname:
const configPath = path.join(__dirname, "config.json");
console.log("Config would load from:", configPath);

Timers: setTimeout, setInterval, setImmediate

Node provides three scheduling functions, each with a matching clear-function:

  • setTimeout(fn, ms) — run once, after at least ms milliseconds
  • setInterval(fn, ms) — run repeatedly, every ms milliseconds, until cleared
  • setImmediate(fn) — run once, right after the current event-loop turn's I/O completes; sooner than any timeout

Delays are minimums, not guarantees — a busy event loop delays callbacks. Each function returns a handle you pass to clearTimeout / clearInterval / clearImmediate to cancel.

Scheduling and cancelling
// Repeat every 100ms, stop after 3 ticks:
let ticks = 0;
const interval = setInterval(() => {
  ticks++;
  console.log("tick", ticks);
  if (ticks === 3) {
    clearInterval(interval);
    console.log("interval cleared");
  }
}, 100);

setImmediate(() => console.log("setImmediate ran before the first tick"));

process.nextTick: the queue jumper

process.nextTick(fn) schedules fn to run before any timer, immediate, or I/O callback — immediately after the currently executing operation finishes. It even runs before promise callbacks in the microtask queue.

Use it sparingly. Its legitimate purpose is making an API *consistently asynchronous* (never calling a callback synchronously on some paths and asynchronously on others). Abusing it can starve the event loop, because nextTick callbacks that schedule more nextTicks never let I/O run.

The full priority ladder
setTimeout(() => console.log("4: setTimeout"), 0);
setImmediate(() => console.log("5: setImmediate"));
Promise.resolve().then(() => console.log("3: promise"));
process.nextTick(() => console.log("2: nextTick"));
console.log("1: synchronous");

// nextTick beats promises; both beat timers and immediates.

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

What is the difference between __dirname and process.cwd()?