The util Module

Small Helpers That Round Out the Standard Library

The util Module

util.parseArgs, util.promisify, util.inspect, util.styleText — the swiss-army knife.

3 min read Level 1/5 #nodejs#util#helpers
What you'll learn
  • Use the most-useful util helpers
  • Style terminal output
  • Inspect objects deeply

node:util is a grab-bag of small helpers. Three you’ll reach for often: parseArgs, promisify, inspect/styleText.

parseArgs

Covered in the args lesson — flag parsing with no dependency.

import { parseArgs } from "node:util";
const { values } = parseArgs({
  options: { name: { type: "string", short: "n" } }
});

promisify

Wrap a callback-based function as a promise:

import { promisify } from "node:util";
import { exec } from "node:child_process";

const run = promisify(exec);

const { stdout } = await run("ls -la");
console.log(stdout);

inspect

Deep object printer. console.log already uses it internally, but sometimes you want it directly:

import { inspect } from "node:util";

const obj = { a: 1, nested: { b: 2, c: { d: 3 } } };
console.log(inspect(obj, { depth: null, colors: true }));

depth: null shows infinite nesting; colors: true adds ANSI colors when the output is a TTY.

styleText (New)

Color terminal output without ANSI escapes by hand:

import { styleText } from "node:util";

console.log(styleText("red", "ERROR"));
console.log(styleText(["bold", "green"], "OK"));

In Node 22+ this is the built-in way to colorize output. No chalk needed.

util.types

Type-checking helpers:

import { types } from "node:util";

types.isPromise(Promise.resolve(1));   // true
types.isDate(new Date());              // true
types.isRegExp(/x/);                   // true

More precise than instanceof across realm boundaries.

End of Chapter

That wraps the standard library. Next chapter: the asynchronous soul of Node — the event loop, workers, processes.

The Event Loop →