devnotes.

Global Objects in Node.js

Browsers give you window — a global object holding things available everywhere in browser JavaScript. Node.js has its own equivalent, plus several standalone globals available in every file without a single require().

The ones you'll actually use

console.log('Hello');              // logging, available everywhere
console.log(__dirname);            // absolute path of the current file's folder
console.log(__filename);           // absolute path of the current file itself

setTimeout(() => {}, 1000);        // schedule a one-time delayed call
setInterval(() => {}, 1000);       // schedule a repeating call

console.log(process.pid);          // the running process's ID
console.log(process.env.HOME);     // read an environment variable

const buf = Buffer.from('hi');     // work with raw binary data

__dirname and __filename in particular save you from ever hardcoding a path — since a project can be moved or deployed to a different location, hardcoded absolute paths break, while __dirname always reflects wherever the file actually is right now:

const path = require('path');
const configPath = path.join(__dirname, 'config.json'); // always correct, wherever the app runs

Attaching to the global object directly

Node.js's actual global object is called global (the counterpart to a browser's window), and anything attached to it is reachable from every file in the app without require():

global.appName = 'Inventory Tracker';

// in a completely different file, no import needed:
console.log(appName); // 'Inventory Tracker'

Why you should almost never actually do that

This works, but it's worth resisting. A variable set on global can be read or overwritten from literally anywhere in the codebase, which makes bugs harder to trace (any file could be the culprit) and testing harder (a test can't isolate a module from hidden global state). The far more common, better-behaved alternative is a small custom module:

// config.js
module.exports = { appName: 'Inventory Tracker' };
// anywhere else
const { appName } = require('./config');

Same result, but now every file that uses appName explicitly says so via its own require() line — easy to trace, easy to test in isolation.

The practical takeaway

Lean on the built-in globals (console, process, __dirname, Buffer, the timer functions) freely — they're a core part of how Node.js works. Avoid attaching your own data to the global object; a proper module almost always serves the same purpose more safely.

Global Objects in Node.js | DevNotes