Node.js Course
Node.js
/
Beginner

Global Objects

Definition

Variables and functions that are globally available in all Node.js modules without needing to be imported via `require()`.

Explain Like I'm New

These are built-in cheat codes. Instead of importing `console` or `setTimeout` into every single file, Node injects them globally so you can use them immediately anywhere in your app.

Real World Example

Using `__dirname` to dynamically find the current folder path so you can read a configuration file safely, regardless of where the app was launched from.

Common Use Cases

  • •Path resolution
  • •Timers
  • •Environment variable access

Terminal Output

bash / terminal
// GLOBAL VARIABLES (No imports needed!) // 1. console (Prints to stdout/stderr) console.log("I am globally available!"); // 2. Timers // setTimeout(() => console.log("Timer finished"), 1000); // 3. Current Directory and File (In CommonJS) // Note: These don't work in standard ES Modules unless specifically enabled console.log("Current Directory:", __dirname); console.log("Current File:", __filename); // 4. The 'process' object (Information about the running app) console.log("Node Version:", process.version); console.log("Platform:", process.platform); // 5. The actual root global object (equivalent to 'window' in browsers) // You can attach things to it (but it's considered bad practice) global.myCustomAppSecret = "12345"; console.log(global.myCustomAppSecret);

Interview Questions

basic

  • Name three global objects in Node.js.

intermediate

  • What is the difference between `__dirname` and `__filename`?

advanced

  • Are `module`, `require`, and `exports` truly global objects?

Flash Cards

Question

Difference between __dirname and __filename?

Click to reveal answer
Answer

`__dirname` gives you the absolute path to the directory (folder) the current file lives in. `__filename` gives you the absolute path to the actual file itself (including the .js extension).

Question

Are require and module truly global?

Click to reveal answer
Answer

Trick question! No. They appear global, but Node actually wraps every single file in a hidden function before executing it. `require`, `exports`, and `__dirname` are actually just arguments passed into that hidden wrapper function!