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.


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