Global Objects in Node.js: Built-in Globals and Utilities

Node.js provides a set of global objects and variables that are accessible across all modules. Some variables, such as __dirname and __filename, appear global but are only valid within the scope of CommonJS modules. In addition, Node.js includes classes and utilities like AbortController, Buffer, BroadcastChannel, fetch, and localStorage, which combine Node.js-specific features with browser-compatible APIs.

__dirname / __filename / exports / module / requireAbortController / AbortSignalBuffer / BlobBroadcastChannel / MessageChannel / MessagePortconsole / clearTimeout / clearInterval / clearImmediate

~3 دقیقه مطالعه · آخرین به‌روزرسانی ۸ دی ۱۴۰۴

1. CommonJS Variables


These variables are only valid within the scope of CommonJS modules:


  • __dirname: Path of the current module’s directory.
  • __filename: Full path of the current file.
  • exports: Module exports.
  • module: Current module object.
  • require(): Used to import modules.

2. AbortController and AbortSignal


Utility for canceling Promise-based operations. Key methods:


  • abort(): Triggers the abort signal.
  • AbortSignal.abort(): Creates an already-aborted signal.
  • AbortSignal.timeout(): Aborts after a specified delay.
  • AbortSignal.any(): Combines multiple signals.

3. Buffer and Blob


Buffer is used for handling binary data. Blob manages file-like data objects.


4. Browser-Compatible Utilities


  • BroadcastChannel: Enables communication between contexts.
  • MessageChannel, MessagePort, MessageEvent: Facilitate inter-thread or inter-process communication.
  • EventTarget and CustomEvent: Event handling APIs.

5. Timer Functions


  • clearTimeout()
  • clearInterval()
  • clearImmediate()

6. console


Used to print output to stdout and stderr.


7. fetch and Related Classes


Browser-compatible implementation of HTTP requests. Related classes:


  • FormData
  • Headers
  • Request
  • Response

8. global and globalThis


global is the legacy global object. globalThis is the modern, standardized replacement.


9. localStorage


Provides key-value storage similar to browsers. Limit: 10 MB.


10. Navigator


Partial implementation of the browser Navigator API. Key property: navigator.hardwareConcurrency shows the number of logical processors available.


Conclusion


Global objects in Node.js combine Node-specific features with browser-compatible APIs. Proper use of these globals enhances efficiency and simplifies application development.


1. Navigator Properties


  • navigator.language: Preferred language of the Node.js instance.
  • navigator.languages: Array of preferred languages.
  • navigator.platform: Identifies the current platform.
  • navigator.userAgent: Runtime name and version (e.g., "Node.js/21").
  • navigator.locks: LockManager for coordinating shared resources.

2. Performance API


Classes like PerformanceEntry, PerformanceMark, PerformanceMeasure, and PerformanceObserver provide tools for measuring and monitoring performance. The performance object comes from the perf_hooks module.


3. process


The process object provides information and control over the Node.js runtime.


4. queueMicrotask()


Queues a microtask for execution. Similar to process.nextTick(), but managed by V8.


5. Stream APIs


  • ReadableStream: Represents a readable stream.
  • WritableStream: Represents a writable stream.
  • Related classes include ReadableStreamDefaultReader and WritableStreamDefaultWriter.

6. Storage APIs


  • sessionStorage: In-memory storage with a 10 MB limit.
  • localStorage: Persistent storage backed by a file.
  • Storage: Browser-compatible implementation.

7. structuredClone()


WHATWG standard method for deep cloning objects.


8. Encoding and Decoding


  • TextEncoder and TextDecoder: Encode and decode text.
  • Stream variants: TextEncoderStream and TextDecoderStream.

9. URL APIs


  • URL: Standard class for managing addresses.
  • URLSearchParams: Manage query parameters.
  • URLPattern: Experimental support for URL pattern matching.

10. WebAssembly and WebSocket


WebAssembly enables low-level code execution, while WebSocket provides real-time communication compatible with browsers.


Conclusion


Global Objects in Node.js combine Node-specific features with browser-compatible APIs. These capabilities allow developers to use a unified set of tools across server-side and browser-like environments, enhancing flexibility and efficiency.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

ادامه

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

ادامه

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

ادامه

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

ادامه

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

ادامه

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

ادامه