Global Objects

Node provides globals available in every file without importing.

Syntaxglobal.myValue = 123;

Some objects are global in Node — available in every file without a require. The most useful are:

  • console — logging.
  • process — information about the running program.
  • global — the global namespace (like window in browsers).
  • __dirname and __filename — the current folder and file (CommonJS only).
  • Timers: setTimeout, setInterval, setImmediate.

Example

Example · javascript
console.log('Platform:', process.platform);
console.log('Node version:', process.version);
console.log('Current file:', __filename);

global.appName = 'Demo';
console.log(global.appName); // Demo

When to use it

  • A developer uses `global.logger` to attach a singleton logger instance so it is accessible in every module without a `require()` call.
  • A script inspects `process.memoryUsage()` in a global health-check endpoint to surface memory pressure before an OOM crash occurs.
  • A test framework polyfills `global.fetch` so integration tests can call the same API surface as browser code without changes.

More examples

Common global objects

Lists the most frequently used Node.js globals -- available in every module without `require()`.

Example · js
console.log(typeof global);          // 'object'
console.log(typeof process);         // 'object'
console.log(typeof Buffer);          // 'function'
console.log(typeof setTimeout);      // 'function'

Set a global variable

Attaches a value to `global` so it is accessible in every module -- use sparingly to avoid hidden coupling.

Example · js
// app.js
global.APP_NAME = 'MyService';

// anywhere else in the process
console.log(APP_NAME); // 'MyService'

Inspect memory usage

Uses `process.memoryUsage()` (a global process method) to report current heap and RSS metrics.

Example · js
const mem = process.memoryUsage();
console.log('Heap used:',  (mem.heapUsed  / 1024 / 1024).toFixed(2), 'MB');
console.log('Heap total:', (mem.heapTotal / 1024 / 1024).toFixed(2), 'MB');
console.log('RSS:',        (mem.rss       / 1024 / 1024).toFixed(2), 'MB');

Discussion

  • Be the first to comment on this lesson.