Global Objects: The Context of Execution
When transitioning from client-side JavaScript to Node.js, the biggest shift is understanding the **context**. In the browser, you have `window`, representing the tab. In Node.js, you have the **Process** and the **Module System**. Understanding global objects is not just about knowing syntax; it's about understanding how your code interacts with the Operating System.
The Tale of Two Paths: `__dirname` vs `process.cwd()`
One of the most common bugs in Node.js applications arises from confusing where a file *is* versus where the command was *run*.
- `__dirname`: This value is baked into the module wrapper. It always refers to the directory where the current script file resides. If you move the script, this value changes to reflect the new location.
- `process.cwd()`: This returns the "Current Working Directory" of the Node.js process. This typically means the folder where you typed `node index.js`.
Scenario: You write a script inside `/app/utils/logger.js` that reads a config file in the same folder. If you use `process.cwd()` and run the script from `/app`, the script will look for the config in `/app`, not `/app/utils`. Always use `path.join(__dirname, 'config.json')` for relative file access.
The Twelve-Factor App: `process.env`
Modern applications must be portable. They shouldn't contain hardcoded database passwords or API keys. The `process.env` object is your gateway to **Environment Variables**.
✔️ Good Practice
const PORT = process.env.PORT || 3000;
const DB_HOST = process.env.DB_HOST;Configuration is injected from outside the code.
❌ Bad Practice
const PORT = 3000;
const DB_HOST = "192.168.1.55";Hardcoded values break when deploying to production.
Expert Tip: The `require` function is synchronous. This means it blocks the event loop until the file is loaded. While acceptable at startup time (top of the file), strictly avoid using `require` inside route handlers or frequent loops, as it will kill your server's performance.