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)

APIUse
util.callbackify(asyncFn)Convert to (err, val) => ...

3. Formatting Strings (util.format)

SpecifierMeaning
%sString
%d / %iNumber / integer
%fFloat
%jJSON
%o / %OInspect (compact / full)
%cCSS (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 }));
OptionUse
depthRecursion limit (default 2)
colorsANSI colors
maxArrayLengthTruncate
showHiddenNon-enumerables
gettersInvoke getters

5. Checking Types

CheckIdiomatic Way
ArrayArray.isArray(x)
BufferBuffer.isBuffer(x)
Date / RegExp / Errorutil.types.isDate / isRegExp / isNativeError
Promiseutil.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)

APIBehavior
util.deprecate(fn, "msg", "DEP0001")Emits warning on first call
--no-deprecationSilence warnings
--throw-deprecationThrow instead of warn

9. Using parseArgs for CLI (util.parseArgs)

Option FieldUse
type"string" or "boolean"
shortSingle-char alias
multipleCollect array
defaultFallback value

10. Using isDeepStrictEqual for Comparison

Example

import util from "node:util";
util.isDeepStrictEqual({ a: [1] }, { a: [1] }); // true

11. Using MIMEType for Content Types

APIReturns
new util.MIMEType("text/html; charset=utf-8")Parsed object
.type / .subtype / .paramsComponents
.params.get("charset")utf-8