Topic 22 of 55
Global Object vs Browser Window
Overview
In the browser, the top-level scope is the `window` object. In Node.js, it is the `global` object. Node.js also provides module-level variables like `__dirname` and `__filename` that look global but are actually local to each file.
Syntax
javascript
// In Node.js, 'global' is the equivalent of 'window'
global.myCustomVariable = "Shared state";
// Standard globals available everywhere in Node without requiring:
console.log("Standard output");
setTimeout(() => console.log("Timer"), 1000);
const buf = Buffer.from("Hello"); // Buffer is a global class
// Pseudo-globals (Module scope variables injected by Node):
console.log(__dirname); // Absolute path to the current directory
console.log(__filename); // Absolute path to the current file
console.log(module); // Reference to the current moduleCommon Pitfalls
- In Node.js, variables declared with `var`, `let`, or `const` at the top level are scoped to the module, NOT added to the `global` object (unlike `window` in the browser).
- Avoid polluting the `global` object. It creates hidden dependencies and makes debugging very difficult.
Real-World Example
Polyfilling standard Web APIs using the global object:
example
javascript
// Sometimes older Node versions lack modern Web APIs.
// You can polyfill them onto the global object to emulate browser behavior.
if (!global.fetch) {
// node-fetch is a popular third-party package
global.fetch = require('node-fetch');
}
// Now fetch() works everywhere in your Node app just like the browser
fetch('https://api.github.com/users/octocat')
.then(res => res.json())
.then(console.log);