The util module

Intermediate · 5 min

promisify and callbackify, inspect and format for readable output, parseArgs, styleText, util.types, deprecate and isDeepStrictEqual.

Before thisEvents and EventEmitterBuffers and binary data

Angular University · 5 min

The util module

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Angular UniversityReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `util.promisify(fn)` converts an error-first callback function into one that returns a promise. `util.callbackify` goes the other way. Most of Node's core APIs now have promise versions, so `promisify` matters mostly for older libraries and your own callback code.
  • `util.inspect(value, options)` is what `console.log` uses to print objects. Its `depth`, `breakLength`, `maxArrayLength` and `colors` options control output, and a `[util.inspect.custom]` method lets a class decide how it prints. `util.format` implements `%s`, `%d`, `%j` and `%o`.
  • `util.parseArgs` parses command-line flags with no dependency: string and boolean options, short aliases, `multiple`, defaults and positionals. Unknown flags throw `ERR_PARSE_ARGS_UNKNOWN_OPTION` unless you set `strict: false`.
  • `util.styleText(format, text)` adds ANSI colours and styles. By default it checks whether the target stream is a terminal and honours `NO_COLOR`, so piped output stays clean.
  • `util.deprecate(fn, message, code)` wraps a function so it prints a `DeprecationWarning` once on first use. `util.types` offers reliable checks (`isPromise`, `isRegExp`, `isProxy`) and `util.isDeepStrictEqual` compares by structure.

A grab bag with a purpose

node:util collects small tools that did not belong anywhere else. Five of them earn their place in everyday code. This lesson was run on Node 26.13.1.

promisify and callbackify

Before promises, Node standardised on error-first callbacks: the last argument is a function called with (err, result). Error-first callbacks and promisify covers the convention in depth. promisify turns any function that follows it into one that returns a promise:

import { promisify } from 'node:util';
import { readFile } from 'node:fs';

const readFileP = promisify(readFile);
const text = await readFileP('notes.txt', 'utf8');

function legacy(x, cb) { setTimeout(() => cb(null, x * 2), 5); }
console.log(await promisify(legacy)(21));      // 42

The video for this lesson shows exactly this conversion of a callback-based API. Today, node:fs/promises, node:timers/promises and node:dns/promises already ship promise versions, so you will reach for promisify mainly with older libraries. When a function does not follow the convention, define the promise form yourself with fn[promisify.custom] = () => Promise.resolve(...). util.callbackify(asyncFn) does the reverse, for APIs that still demand a callback.

inspect and format

console.log prints objects through util.inspect, and knowing its options explains most “why is this printing [Object]” moments:

import { inspect, format } from 'node:util';

const nested = { a: { b: { c: { d: 1 } } }, list: Array.from({ length: 120 }, (_, i) => i) };
console.log(inspect(nested, { depth: 0 }));                      // { a: [Object], list: [Array] }
console.log(inspect(nested, { depth: null, maxArrayLength: 3 }));  // full depth, array cut to 3 items

The default depth is 2, which is why deep structures show [Object]. depth: null removes the limit, maxArrayLength truncates long arrays, breakLength controls line wrapping, and colors: true adds colour. A class can control its own printing:

class Point {
  constructor(x) { this.x = x; }
  [inspect.custom]() { return `Point<${this.x}>`; }
}
console.log(inspect({ p: new Point(1) }));   // { p: Point<1> }

util.format is the engine behind console.log('%s is %d', name, n): %s string, %d number, %i integer, %j JSON, %o object, %% a literal percent sign. Extra arguments are appended.

parseArgs

Parsing process.argv by hand gets ugly after the second flag. parseArgs is built in:

import { parseArgs } from 'node:util';

const { values, positionals } = parseArgs({
  args: ['build', '--out', 'dist', '-v', '--tag=a', '--tag=b', 'x'],
  allowPositionals: true,
  options: {
    out: { type: 'string', short: 'o' },
    verbose: { type: 'boolean', short: 'v' },
    tag: { type: 'string', multiple: true },
    port: { type: 'string', default: '3000' },
  },
});
// values:      { out: 'dist', verbose: true, tag: ['a', 'b'], port: '3000' }
// positionals: ['build', 'x']

In your own script omit args and it reads process.argv.slice(2). Unknown flags throw ERR_PARSE_ARGS_UNKNOWN_OPTION by default, which is usually what you want. Note that values are strings; convert numbers yourself. Building command-line tools builds a full tool on it.

styleText

For coloured terminal output without installing chalk:

import { styleText } from 'node:util';
console.log(styleText('red', 'error:'), 'something failed');
console.log(styleText(['bold', 'green'], 'ok'));

It checks that the destination stream is a terminal and respects NO_COLOR and FORCE_COLOR, so redirecting to a file produces err, not escape codes. In testing with the output piped, styleText('red', 'err') returned plain "err", and { validateStream: false } forced the escape codes. It is safest to decide colour centrally and not scatter escape sequences through your code.

types, isDeepStrictEqual and deprecate

util.types has checks that work across realms and cannot be fooled by look-alike objects: isPromise, isRegExp, isDate, isTypedArray, isProxy and more. util.isDeepStrictEqual(a, b) compares by structure, using strict equality for primitives, and is what assert.deepStrictEqual uses.

If you maintain a library, util.deprecate marks a function as on its way out:

import { deprecate } from 'node:util';
const old = deprecate(() => 'result', 'oldFn() is deprecated, use newFn()', 'DEP_ME_001');
old(); old();

Node prints [DEP_ME_001] DeprecationWarning: oldFn() is deprecated, use newFn() once, and only on the first call. --trace-deprecation shows where it was triggered, and --no-deprecation silences them.

Two newer additions: util.parseEnv(content) parses .env-format text into an object, and util.debuglog('myapp') returns a logging function that prints only when the environment variable NODE_DEBUG=myapp is set, which gives libraries a zero-cost debug channel.

What the video covers

Angular University’s five-minute video from 2017 demonstrates util.promisify converting a callback-based API to a promise-based one. That is one of five topics here; inspect, format, parseArgs, styleText, types and deprecate come from the prose and were all run on Node 26.13.1. No better video on the module existed: searches for it returned auto-generated shorts and an eight-year-old 53-minute meetup talk. The promisify demo is dated but accurate, since promisify has not changed. No transcript was available. This is a weak pick, flagged on purpose.

Where this fits

util is the toolbox the next lessons keep reaching into. Hashing, HMAC and randomness is next, and building command-line tools ties parseArgs and styleText together. The asynchronous side of promisify continues in error-first callbacks and promisify. For JavaScript’s own callback story, see callbacks and callback hell.

Check yourself

  1. 01You have `readFile(path, cb)` from an older library. How do you turn it into something you can `await`, and what does the original need to follow?

    Call `const readFileP = util.promisify(readFile)` and `await readFileP(path)`. The function must take its callback as the last argument and call it with `(err, result)`, error first. If it follows another convention, attach a `[util.promisify.custom]` function to define the promise form yourself.

  2. 02`console.log(obj)` prints `[Object]` for a deeply nested property. How do you see all of it?

    `console.log` uses `util.inspect`, which stops at depth 2 by default. Call `util.inspect(obj, { depth: null })` (or `console.dir(obj, { depth: null })`) to print the whole structure.

  3. 03Why does `util.styleText('red', 'error')` return plain `error` when you pipe a script's output into a file?

    By default `styleText` checks whether the stream it will be written to is a terminal and respects `NO_COLOR`, and strips colour when it is not. Pass `validateStream: false` to force the escape codes. That default is why coloured logs do not show up as `\u001b[31m` garbage in files and CI logs.

  4. 04What does `util.deprecate` do when the wrapped function is called twice?

    It prints the `DeprecationWarning` once, on the first call, and then just calls through. Giving the warning a code (such as `'DEP_ME_001'`) lets users find or silence it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark