Working with Globals

1. Using __dirname and __filename

VariableValueModule
__dirnameAbsolute dir path of current fileCommonJS only
__filenameAbsolute file pathCommonJS only
import.meta.dirnameEquivalent in ES modules v20.11+ESM
import.meta.filenameESM equivalent v20.11+ESM

2. Understanding global Object

PropertyDescription
globalTop-level scope object in Node (like window)
global.foo = 1Assign cross-module global (avoid)

3. Using globalThis

Note: globalThis is the cross-environment standard. Prefer it over global for portable code (works in browser, Worker, Node).
EnvironmentResolves To
Nodeglobal
Browserwindow
Workerself

4. Using console Methods

MethodOutput StreamUse
console.logstdoutGeneral logs
console.errorstderrErrors
console.warnstderrWarnings
console.infostdoutInfo
console.debugstdoutDebug (when enabled)
console.table(arr)stdoutTabular output
console.time/timeEndstdoutMeasure duration
console.tracestderrStack trace
console.dir(obj, opts)stdoutInspect with options
console.group/groupEndstdoutIndented blocks
console.assert(cond, msg)stderrPrint if cond falsy

5. Using Buffer Global

ConstructorPurpose
Buffer.from(str, "utf8")From string
Buffer.alloc(size)Zero-filled bytes
Buffer.allocUnsafe(size)Faster, uninitialized memory

6. Using process Global

PropertyDescription
process.argvCLI arguments
process.envEnvironment variables
process.cwd()Current working dir
process.platformlinux / darwin / win32
process.exit(code)Exit with code

7. Using setTimeout/setInterval Globals

APIReturnsCancel With
setTimeout(fn, ms)Timeout objectclearTimeout
setInterval(fn, ms)Timeout objectclearInterval
setImmediate(fn)ImmediateclearImmediate
queueMicrotask(fn)voidn/a

8. Understanding module Object

PropertyDescription
module.exportsWhat this module exports
module.idIdentifier (filename)
module.filenameAbsolute path
module.childrenModules required by this one
module.pathsLookup paths

9. Using require Function

FormResolves To
require("fs")Built-in module
require("./util")Local file
require("lodash")node_modules package
require.resolve("x")Get resolved path
require.cacheLoaded modules cache

10. Using exports and module.exports

Example: Two export patterns

// Single export
module.exports = function greet(name) { return "Hi " + name; };

// Multiple named exports
exports.add = (a, b) => a + b;
exports.sub = (a, b) => a - b;
FormWhen
module.exports = XReplacing entire export
exports.foo = XAdding to default export object
Warning: Reassigning exports = ... breaks the binding. Always use module.exports = ....

11. Avoiding Global Variable Pollution

Anti-patternFix
global.db = ...Pass via DI / module export
Implicit globals (no const)Use "use strict" / ESM (strict by default)
Monkey-patching globalsWrap in dedicated modules