~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.MIMETypeutil.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 codesutil.styleText()— apply ANSI color stylesutil.toUSVString()— fix invalid Unicode surrogatesutil.parseEnv()— parse .env filesutil.getCallSites()— stack traces with source map support
14. Legacy / Deprecated APIs
util.inherits()→ useclass extendsutil.isArray()→ useArray.isArray()util._extend()→ useObject.assign()
15. Best Practices
- Use
util.inspect()for rich debugging output. - Use
promisifyto modernize callback APIs. - Use
debuglogfor conditional debug output. - Use
parseArgsfor clean CLI tools. - Use
util.typesfor 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.
نوشته و پژوهش شده توسط دکتر شاهین صیامی