💻 Understanding the Global Object in Node.js
When working in Node.js, one of the most important things to understand is the global object. Unlike browsers where the global scope is attached to the window object, in Node.js it's slightly different — and more powerful in some ways.
Let’s break it down.
💻 What Is the Global Object?
In Node.js, the global object is named global. It provides a set of built-in modules, functions, and values that are available from anywhere in your application — no need to import or require them.
It is similar to window in the browser, but it's more tailored to server-side needs.
console.log(global); // Outputs the entire global object
💻 Common Global Variables
Here are some of the most used global values in Node.js:
Name | Description |
---|---|
__dirname | Absolute path of the folder containing the current file |
__filename | Absolute path of the current file |
global | The global object itself |
module | Info about the current module |
exports | Shortcut to module.exports |
require() | Function to import modules |
setTimeout() | Delays code execution |
setInterval() | Repeats code at intervals |
console | Standard logging interface |
💻 Example: Using Global Values
console.log(__dirname); // Prints the folder path
console.log(__filename); // Prints the full file path
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
You don’t need to import anything for these to work — they are available globally.
⚠️ Note on Scope
Unlike in the browser, variables defined in a Node.js file are not added to the global object by default. Each file is a separate module, so the variables are scoped locally unless you explicitly assign them to global.
let name = "NodeJs";
console.log(global.name); // undefined
global.name = "NodeJs";
console.log(global.name); // "NodeJs"
🚫 Don’t Overuse global
While global can be helpful, overusing it is considered bad practice. It can lead to conflicts and unpredictable behavior in larger applications.
Use it only when a value truly needs to be shared across all files, like configuration data or utility functions.
✅ In Summary
- global is to Node.js what window is to browsers.
- It contains many helpful built-in tools.
- Use with care — prefer module exports for sharing logic.