Node.js theorytheory 0/50 · 0%
Foundations · easy

18. Global objects and scope

globalThis, __dirname/__filename, and module-level scope.

Node wraps every CommonJS module in a function, giving each file its own local scope plus a few module-level variables: `__dirname`, `__filename`, `module`, `exports`, and `require`. These do not exist in ESM files, where you instead derive equivalents from `import.meta.url`.

js
// CommonJS
console.log(__dirname, __filename);

// ESM equivalent
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

`globalThis` is the standard way to reach the true global object across JS environments (browser `window`, worker `self`, Node's `global`), useful for writing isomorphic code that must run in more than one environment.

Check your understanding

  1. 1. Are __dirname and __filename available in native ESM files?

  2. 2. What does globalThis provide?

  3. 3. Why is each CommonJS file's top-level 'var' not visible in another file?