Node.js Util Module
Node.js Util Module
The util module in Node.js provides helper functions that make it easier to work with asynchronous operations, debugging, inheritance, formatting, and more.
It is a core module, so no installation is required.
✔️ Importing the Util Module
CommonJS
ES Module
🚀 Most Useful Util Module Features
1. util.format()
Formats a string similar to printf in C.
Format specifiers:
%s – string
%d – number
%j – JSON
%% – percent sign
2. util.promisify()
Converts a callback-based function into a Promise-based one.
Example:
3. util.callbackify()
Converts a promise-based function into a callback-style function.
4. util.inherits()
Helps one constructor inherit from another (older way).
✔️ Prefer ES6 class extends instead.
5. util.debuglog()
Creates a debug function that logs only when an environment variable is set.
Run with:
6. util.types
Contains type-checking functions.
Examples:
7. util.inspect()
Returns a string representation of an object — useful for debugging.
Useful options:
depth – recursion level
colors – colored output
showHidden – include non-enumerable properties
8. util.TextEncoder / util.TextDecoder
Encodes/decodes text (like browser API).
9. util.parseArgs()
Helps parse command line arguments (added in Node 18+).
⭐ Summary Table
| Feature | Purpose |
|---|---|
format() | String formatting |
promisify() | Convert callback → Promise |
callbackify() | Convert Promise → callback |
inherits() | Set up prototype inheritance |
debuglog() | Conditional debug logging |
types | Type checking utilities |
inspect() | Object debugging |
TextEncoder/TextDecoder | Encode/decode text |
parseArgs() | Parse CLI arguments |
