Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Node.js Dictionary
  3. Global Objects

Global Objects

Node.js provides global objects and global functions that are available from the start without writing require at the top of a file. The most common ones are global and globalThis (equivalent to the browser's window), __dirname and __filename (holding information about the running file), require, module, and exports for module management, the timers setTimeout, setInterval, and setImmediate, and Buffer for handling binary data.

Main Global Objects

GlobalDescription
__dirnameThe absolute path of the directory containing the currently running file. Used for path resolution.
__filenameThe absolute path of the currently running file.
globalThe global object in Node.js. Equivalent to window in the browser.
globalThisA standard way to reference the global object regardless of environment (Node.js v12 and later).
require(id)Loads a module. You can specify built-in modules, npm packages, or files by relative path.
moduleAn object representing the current module itself. Set the exported value via module.exports.
exportsAn initial reference to module.exports. You can add properties to it to export them.
processAn object representing the Node.js process itself. Provides access to command-line arguments, environment variables, exit codes, and more.
consoleAn object for writing to standard output and standard error. Same as the browser's console.
BufferA class for handling binary data. Used for file I/O and network communication.
setTimeout(fn, ms)Executes a function once after the specified number of milliseconds.
setInterval(fn, ms)Repeatedly executes a function at the specified interval in milliseconds.
clearTimeout(id)Cancels a timer created with setTimeout.
clearInterval(id)Cancels a timer created with setInterval.
setImmediate(fn)Executes a function after the current event loop iteration completes.
queueMicrotask(fn)Adds a function to the microtask queue. Runs at the same timing as Promise then.
URLA class for parsing and manipulating URLs (global since Node.js v10).
URLSearchParamsA class for manipulating URL query parameters (global since Node.js v10).
cryptoCryptographic utilities (global since Node.js v19).

__dirname / __filename — Getting File Paths

__dirname is the absolute path of the directory containing the current file, and __filename is the absolute path of the file itself. They are useful when loading another file with require() or when dynamically determining where to save a file.

path_info.js
var path = require('path');

console.log('__filename:', __filename);
console.log('__dirname: ', __dirname);

// Combine with the path module to build paths
var dataDir  = path.join(__dirname, 'data');
var logFile  = path.join(__dirname, 'logs', 'kiryu.log');
var relative = path.relative(__dirname, '/var/www/kiryu');

console.log('data directory:', dataDir);
console.log('log file:', logFile);
console.log('relative path:', relative);

// Get extension and filename
console.log('filename:', path.basename(__filename));
console.log('extension:', path.extname(__filename));
console.log('directory name:', path.dirname(__filename));
node path_info.js
__filename: /home/kiryu/projects/path_info.js
__dirname:  /home/kiryu/projects
data directory: /home/kiryu/projects/data
log file: /home/kiryu/projects/logs/kiryu.log
relative path: ../../var/www/kiryu
filename: path_info.js
extension: .js
directory name: /home/kiryu/projects

process — Process Information and Control

The process object represents the Node.js process itself. It provides access to command-line arguments, environment variables, process ID, and more. You can also terminate the process with process.exit().

process_info.js
// Get command-line arguments (node process_info.js arg1 arg2)
// process.argv[0] = path to the node executable
// process.argv[1] = path to the script
// process.argv[2] and beyond are the arguments passed by the user
var args = process.argv.slice(2);
console.log('args:', args);

// Get environment variables
console.log('NODE_ENV:', process.env.NODE_ENV || 'not set');
console.log('HOME:', process.env.HOME);

// Get process information
console.log('process ID:', process.pid);
console.log('Node.js version:', process.version);
console.log('platform:', process.platform);
console.log('architecture:', process.arch);

// Get memory usage (Like Ryuga Gotoku staff monitoring)
var mem = process.memoryUsage();
console.log('heap used:', Math.round(mem.heapUsed / 1024 / 1024) + ' MB');
console.log('heap total:', Math.round(mem.heapTotal / 1024 / 1024) + ' MB');

// Get the current working directory
console.log('current directory:', process.cwd());

// Exit the process (0 = normal, non-zero = error)
// process.exit(0);
node process_info.js "Kiryu Kazuma" "Majima Goro"
args: [ 'Kiryu Kazuma', 'Majima Goro' ]
NODE_ENV: not set
HOME: /home/kiryu
process ID: 12345
Node.js version: v20.11.0
platform: linux
architecture: x64
heap used: 5 MB
heap total: 16 MB
current directory: /home/kiryu/projects

global / globalThis — Global Scope

The global object in Node.js is global. Assigning to global.propertyName makes the value accessible from any module without require, but overusing global variables can cause unexpected side effects. globalThis is the standard way to reference the global object in both browser and Node.js environments.

global_scope.js
// globalThis works in both browser (window) and Node.js (global)
console.log(globalThis === global); // true in Node.js

// Set a global variable (possible but not recommended)
global.appName = 'Kamurocho Management System';
global.version = '1.0.0';

// Accessible from anywhere (no require needed)
console.log(appName);  // 'Kamurocho Management System'
console.log(version);  // '1.0.0'

// Check existence with typeof (avoids ReferenceError)
console.log(typeof kiryu !== 'undefined' ? kiryu : 'undefined');

// Check what is registered as global
console.log('console is global:', typeof console);
console.log('process is global:', typeof process);
console.log('Buffer is global:', typeof Buffer);
console.log('setTimeout is global:', typeof setTimeout);
console.log('setInterval is global:', typeof setInterval);
node global_scope.js
true
Kamurocho Management System
1.0.0
undefined
console is global: object
process is global: object
Buffer is global: function
setTimeout is global: function
setInterval is global: function

setTimeout / setInterval / setImmediate — Timers

Node.js supports the same setTimeout() and setInterval() as the browser. Additionally, Node.js-specific setImmediate() runs immediately after I/O operations complete — before the next timer fires.

timers.js
// setTimeout: run once after 500ms
var timer1 = setTimeout(function() {
    console.log('Kiryu Kazuma: Understood. (after 500ms)');
}, 500);

// setInterval: repeat every 200ms (stop after 3 times)
var count = 0;
var timer2 = setInterval(function() {
    count++;
    console.log('Majima Goro: Hey, bro! (' + count + ')');
    if (count >= 3) {
        clearInterval(timer2); // cancel the timer
        console.log("Majima's interval ended");
    }
}, 200);

// setImmediate: run right after the current event loop iteration
setImmediate(function() {
    console.log('Kasuga Ichiban: setImmediate (right after I/O)');
});

// Synchronous code runs first
console.log('Nishikiyama Akira: sync (first)');

// queueMicrotask: runs at the same timing as Promise then
queueMicrotask(function() {
    console.log('Sawamura Haruka: microtask (before setImmediate)');
});
node timers.js
Nishikiyama Akira: sync (first)
Sawamura Haruka: microtask (before setImmediate)
Kasuga Ichiban: setImmediate (right after I/O)
Majima Goro: Hey, bro! (1)
Majima Goro: Hey, bro! (2)
Kiryu Kazuma: Understood. (after 500ms)
Majima Goro: Hey, bro! (3)
Majima's interval ended

Buffer — Binary Data Operations

Buffer is a Node.js-specific class for storing binary data. It is used wherever raw byte sequences are needed — file I/O, network communication, cryptographic processing, and more. It can be used without require().

buffer_basic.js
// Create a Buffer from a string
var buf1 = Buffer.from('Kiryu Kazuma', 'utf8');
console.log('Buffer:', buf1);
console.log('byte length:', buf1.length);
console.log('back to string:', buf1.toString('utf8'));

// Create a Buffer of the specified byte length (zero-filled)
var buf2 = Buffer.alloc(8);
console.log('alloc(8):', buf2);  // <Buffer 00 00 00 00 00 00 00 00>

// Base64 encode/decode
var message = 'Guardian of Kamurocho: Majima Goro';
var encoded = Buffer.from(message, 'utf8').toString('base64');
var decoded = Buffer.from(encoded, 'base64').toString('utf8');
console.log('Base64:', encoded);
console.log('decoded:', decoded);

// Hex representation
var hex = Buffer.from('KIRYU').toString('hex');
console.log('hex:', hex);
console.log('restored from hex:', Buffer.from(hex, 'hex').toString('utf8'));

// Buffer comparison
var a = Buffer.from('Kasuga Ichiban');
var b = Buffer.from('Kasuga Ichiban');
console.log('equals:', a.equals(b)); // true (same content)
console.log('===:', a === b);        // false (different references)
node buffer_basic.js
Buffer: <Buffer 4b 69 72 79 75 20 4b 61 7a 75 6d 61>
byte length: 12
back to string: Kiryu Kazuma
alloc(8): <Buffer 00 00 00 00 00 00 00 00>
Base64: R3VhcmRpYW4gb2YgS2FtdXJvY2hvOiBNYWppbWEgR29ybw==
decoded: Guardian of Kamurocho: Majima Goro
hex: 4b49525955
restored from hex: KIRYU
equals: true
===: false

Overview

Node.js global objects are organized around global (or globalThis), which is equivalent to the browser's window. Under it are process, console, Buffer, timer functions, and more. These can all be used without writing require() at the top of a file.

__dirname and __filename hold different values per module and are essential for accessing the file system and resolving relative paths. However, in ES Modules (.mjs files or projects with "type": "module" in package.json), __dirname and __filename are not defined — use import.meta.url and fileURLToPath() to obtain equivalent values.

The process object is the gateway for accessing command-line arguments (process.argv), environment variables (process.env), process termination (process.exit()), and memory information (process.memoryUsage()). Buffer is a Node.js-specific class that extends Uint8Array and is used for binary data operations.

Common Mistakes

Common Mistake 1: Using __dirname in ES Modules causes ReferenceError

__dirname is a variable specific to CommonJS (the format that uses require() in .js files). It is not defined in ES Modules environments — .mjs files or projects with "type": "module" set in package.json — so referencing it will throw a ReferenceError.

NG example (using __dirname in an ES Modules file):

// Error: ReferenceError: __dirname is not defined
console.log(__dirname);
node app.mjs
ReferenceError: __dirname is not defined

OK example (use import.meta.url to obtain an equivalent value in ES Modules):

import { fileURLToPath } from 'url';
import { dirname } from 'path';

var __filename = fileURLToPath(import.meta.url);
var __dirname  = dirname(fileURLToPath(import.meta.url));

console.log(__dirname);
console.log(__filename);

Common Mistake 2: Adding properties to global causes name collisions in other modules

Setting a value on global.propertyName makes it accessible from anywhere in the application without require(). However, another module may overwrite the same property or accidentally reference it.

NG example (setting a value on global that gets overwritten by another module):

// module_a.js
global.config = { debug: true, user: 'Kiryu Kazuma' };

// module_b.js (loaded later)
global.config = { debug: false }; // module_a's config is lost

OK example (share data by exporting and importing as a module):

// config.js
module.exports = { debug: true, user: 'Kiryu Kazuma' };

// module_a.js
var config = require('./config');
console.log(config.debug); // true

// module_b.js
var config = require('./config');
console.log(config.user); // 'Kiryu Kazuma' (not overwritten)

Writing to the global object creates hidden dependencies between modules. Exporting shared data or configuration as a module and importing it explicitly keeps dependencies clear.

If you find any errors or copyright issues, please .