Working with Util Module
1. Promisifying Callbacks (util.promisify)
Example
import { promisify } from "node:util";
const sleep = promisify(setTimeout);
await sleep(500);
2. Creating Callbackified Functions (util.callbackify)
| API | Use |
|---|---|
util.callbackify(asyncFn) | Convert to (err, val) => ... |
3. Formatting Strings (util.format)
| Specifier | Meaning |
|---|---|
%s | String |
%d / %i | Number / integer |
%f | Float |
%j | JSON |
%o / %O | Inspect (compact / full) |
%c | CSS (no-op in Node) |
4. Inspecting Objects (util.inspect)
Example
import util from "node:util";
console.log(util.inspect(obj, { depth: null, colors: true, compact: false }));
| Option | Use |
|---|---|
depth | Recursion limit (default 2) |
colors | ANSI colors |
maxArrayLength | Truncate |
showHidden | Non-enumerables |
getters | Invoke getters |
5. Checking Types
| Check | Idiomatic Way |
|---|---|
| Array | Array.isArray(x) |
| Buffer | Buffer.isBuffer(x) |
| Date / RegExp / Error | util.types.isDate / isRegExp / isNativeError |
| Promise | util.types.isPromise(x) |
6. Using TextEncoder and TextDecoder
Example
const enc = new TextEncoder();
const bytes = enc.encode("héllo"); // Uint8Array
const dec = new TextDecoder("utf-8");
const str = dec.decode(bytes);
7. Using Debuglog (util.debuglog)
Example: Conditional log
import { debuglog } from "node:util";
const log = debuglog("myapp:db");
log("query took %d ms", elapsed);
// Run with: NODE_DEBUG=myapp:db node app.js
8. Deprecating Functions (util.deprecate)
| API | Behavior |
|---|---|
util.deprecate(fn, "msg", "DEP0001") | Emits warning on first call |
--no-deprecation | Silence warnings |
--throw-deprecation | Throw instead of warn |
9. Using parseArgs for CLI (util.parseArgs)
| Option Field | Use |
|---|---|
type | "string" or "boolean" |
short | Single-char alias |
multiple | Collect array |
default | Fallback value |
10. Using isDeepStrictEqual for Comparison
11. Using MIMEType for Content Types
| API | Returns |
|---|---|
new util.MIMEType("text/html; charset=utf-8") | Parsed object |
.type / .subtype / .params | Components |
.params.get("charset") | utf-8 |