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.

util.inspectutil.promisify / util.callbackifyutil.deprecateutil.formatutil.types

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

1. Introduction


The node:util module provides a wide range of helper functions that simplify debugging, formatting, type detection, and interoperability between callback and Promise APIs.


2. Accessing the Module


const util = require('node:util');
// or
import util from 'node:util';

3. Debugging & Inspection


3.1 util.inspect()


Generates a detailed string representation of any object — ideal for debugging.

console.log(util.inspect(obj, {
  showHidden: true,
  depth: null,
  colors: true
}));

Supports custom inspectors via util.inspect.custom.


3.2 util.debuglog()


Conditional debug logging based on the NODE_DEBUG environment variable.

const log = util.debuglog('myapp');
log('Debug message');

4. Callback ↔ Promise Conversions


4.1 util.promisify()


Converts Node-style callback functions into Promise-based ones.

4.2 util.callbackify()


Converts async/Promise functions into callback-style functions.


5. Deprecation Handling


Wraps a function to emit a DeprecationWarning when used:

const fn = util.deprecate(originalFn, 'This function is deprecated');

6. String Formatting


6.1 util.format()


printf-style formatting using %s, %d, %j, %o, %O, etc.

6.2 util.formatWithOptions()


Same as format() but with inspect options (e.g., colors).


7. Type Checking (util.types)


A fast and comprehensive set of type-checking helpers:

  • isArrayBuffer()
  • isAsyncFunction()
  • isBigInt64Array()
  • isDate()
  • isMap()
  • isPromise()
  • isProxy()
  • isRegExp()
  • isSet()
  • isTypedArray()
  • isUint8Array()
  • isWeakMap()

8. Error & System Information


  • util.getSystemErrorName(err)
  • util.getSystemErrorMap()
  • util.getSystemErrorMessage(err)

9. Text Encoding & Decoding


  • TextEncoder: UTF‑8 only
  • TextDecoder: Supports multiple encodings (depends on ICU)

10. MIME Handling


  • util.MIMEType
  • util.MIMEParams

11. CLI Argument Parsing


A modern argument parser for building command‑line tools:

const args = util.parseArgs({
  options: { verbose: { type: 'boolean' } }
});

12. Abort Controllers & Transferable Signals


  • util.transferableAbortController()
  • util.transferableAbortSignal()
  • util.aborted(signal)

13. Miscellaneous Utilities


  • util.diff() — Myers diff algorithm (experimental)
  • util.stripVTControlCharacters() — remove ANSI control codes
  • util.styleText() — apply ANSI color styles
  • util.toUSVString() — fix invalid Unicode surrogates
  • util.parseEnv() — parse .env files
  • util.getCallSites() — stack traces with source map support

14. Legacy / Deprecated APIs


  • util.inherits() → use class extends
  • util.isArray() → use Array.isArray()
  • util._extend() → use Object.assign()

15. Best Practices


  • Use util.inspect() for rich debugging output.
  • Use promisify to modernize callback APIs.
  • Use debuglog for conditional debug output.
  • Use parseArgs for clean CLI tools.
  • Use util.types for fast, reliable type checks.

Conclusion


The node:util module is a versatile and powerful toolbox for Node.js developers. It enhances debugging, formatting, type checking, CLI development, and interoperability between different programming styles. Mastering this module significantly improves code clarity, maintainability, and developer productivity.


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

مقالات مرتبط

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 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، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

ادامه

Comprehensive Guide to Trace Events and TTY in Node.js

Node.js provides two powerful low‑level modules for diagnostics and terminal interaction: node:trace_events — a high‑resolution tracing system that captures internal activity from V8, Node.js core, and userland code. It is essential for profiling, performance analysis, and deep debugging. node:tty — a module that exposes TTY (terminal) interfaces, enabling advanced CLI tools, raw input handling, cursor control, color detection, and terminal resizing. This guide explains both modules in a clean, structured, and practical way.

ادامه