TExcelTAD
Home › Node.js › Node.js Util Module

Node.js Util Module

The node:util module is a toolbox of small helpers that Node itself uses internally. Some of them you will reach for almost every day: formatting strings, inspecting nested objects, turning old callback APIs into promises, comparing values deeply and parsing command-line arguments.

js
const util = require('node:util');       // CommonJS
import util from 'node:util';             // ES modules
import { promisify, inspect } from 'node:util';

The most useful helpers

Helper What it does
util.format(fmt, ...args) printf-style formatting (%s, %d, %i, %f, %j, %o, %%)
util.inspect(value, options) turns any value into the string console.log would print
util.promisify(fn) wraps a callback-style function so it returns a promise
util.callbackify(fn) the reverse: wraps an async function in a callback API
util.isDeepStrictEqual(a, b) deep comparison of objects, arrays, maps…
util.types.isDate(v) and friends reliable type checks
util.parseArgs(config) parses command-line flags without a library
util.styleText(format, text) adds terminal colours (Node 20.12+)

Formatting strings

util.format() is what console.log uses when its first argument contains % placeholders. You can call it yourself to build a string without printing it:

node · try it yourself
const util = require('node:util');

const msg = util.format('%s has %d items costing %f', 'Cart', 3, 19.5);
console.log(msg);
console.log(util.format('Data: %j', { id: 7, tags: ['a', 'b'] }));
console.log(util.format('%d%% done', 100));
console.log(util.format('extra', 'args', 'are', 'appended'));
Cart has 3 items costing 19.5
Data: {"id":7,"tags":["a","b"]}
100% done
extra args are appended

Inspecting objects

By default console.log stops printing nested objects after two levels and shows [Object] instead. util.inspect() lets you control the depth, sorting, line width and more:

node · try it yourself
const { inspect } = require('node:util');

const config = { server: { http: { port: 8080, tls: { enabled: false } } } };

console.log(inspect(config));
console.log(inspect(config, { depth: null, compact: true, breakLength: Infinity }));
console.log(inspect('quoted string'));
console.log(inspect(new Map([['a', 1]])));
{ server: { http: { port: 8080, tls: [Object] } } }
{ server: { http: { port: 8080, tls: { enabled: false } } } }
'quoted string'
Map(1) { 'a' => 1 }

Tip: console.dir(obj, { depth: null }) is a shortcut for printing an object with unlimited depth.

promisify: callbacks to promises

Many older Node APIs (and npm packages) use error-first callbacks: the last argument is a function called as callback(err, result). promisify converts such a function so you can await it:

node · try it yourself
const { promisify } = require('node:util');

// An old-style API: callback(err, result)
function divide(a, b, callback) {
  setImmediate(() => {
    if (b === 0) callback(new Error('division by zero'));
    else callback(null, a / b);
  });
}

const divideAsync = promisify(divide);

async function main() {
  console.log(await divideAsync(10, 4));
  try {
    await divideAsync(1, 0);
  } catch (err) {
    console.log('Caught:', err.message);
  }
}
main();
2.5
Caught: division by zero

Note: Most built-in modules already have promise versions (node:fs/promises, node:timers/promises, node:dns/promises), so you mainly need promisify for third-party or legacy code.

Deep equality and type checks

=== compares objects by reference. To compare their contents, use isDeepStrictEqual. The util.types namespace has checks that work even across realms (for example, for values coming from a worker or a vm context):

node · try it yourself
const util = require('node:util');

const a = { name: 'Ada', langs: ['js', 'rust'] };
const b = { name: 'Ada', langs: ['js', 'rust'] };

console.log(a === b);
console.log(util.isDeepStrictEqual(a, b));
console.log(util.isDeepStrictEqual([1, 2], ['1', '2']));
console.log(util.types.isPromise(Promise.resolve()));
console.log(util.types.isRegExp(/x/));
false
true
false
true
true

Parsing command-line arguments

util.parseArgs() handles flags like --name Ada -v file.txt, so small CLI tools need no dependency. Here we pass args explicitly; in a real script you would leave it out and it reads process.argv:

node · try it yourself
const { parseArgs } = require('node:util');

const { values, positionals } = parseArgs({
  args: ['--name', 'Ada', '-v', 'notes.txt', '--count=3'],
  options: {
    name: { type: 'string', default: 'World' },
    verbose: { type: 'boolean', short: 'v' },
    count: { type: 'string' },
  },
  allowPositionals: true,
});

console.log(values.name, values.verbose, Number(values.count));
console.log(positionals);
Ada true 3
[ 'notes.txt' ]

Unknown flags throw an error by default (strict: true), which gives your users immediate feedback on typos.

Test yourself

What does util.promisify(fn) require of fn?

  1. It must already return a promise
  2. Its last argument must be an error-first callback
  3. It must be an async function
  4. It must take no arguments

Which call compares two objects by their contents?

  1. a === b
  2. Object.is(a, b)
  3. util.isDeepStrictEqual(a, b)
  4. util.inspect(a) == b

What does util.format('%d%%', 50) return?

  1. '50%%'
  2. '50%'
  3. '%d%'
  4. '50'