Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 133 ยท The Runtime

The util Module

Learn the Node.js util module - promisify and callbackify, inspect and custom inspect, format, types, parseArgs, styleText, deprecate, isDeepStrictEqual and debuglog, with runnable examples.

Every language grows a drawer of small helpers that do not belong anywhere else, and in Node.js that drawer is the node:util module. It holds the function that turns callback APIs into promises, the machinery behind console.log's coloured object printing, a command-line argument parser, a deep-equality check, a way to mark old functions as deprecated, and more. None of it is glamorous, and all of it shows up in real programs.

You import it like any other built-in module, with the node: prefix so nobody can confuse it with an npm package of the same name:

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

This lesson walks through the parts you will actually use: promisify and callbackify for bridging old and new async styles, inspect and format for turning values into text, types for reliable type checks, parseArgs and styleText for command-line tools, isDeepStrictEqual, deprecate, TextDecoder and debuglog. We build on the errors and events lessons, and you will meet parseArgs again in Building Command-Line Tools.

promisify: callbacks to promises

Older Node APIs follow the error-first callback convention: the last argument is a function (err, result) => {}. Modern code prefers promises and async/await. util.promisify converts one into the other without you rewriting the original.

Node.js promisify a callback function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

promisify returns a new function that takes the same arguments minus the callback and returns a promise. When the callback receives a non-null first argument the promise rejects with it; otherwise it resolves with the second argument. The original function is untouched.

Two details matter. First, promisify relies on the error-first convention, so it only works for callbacks shaped that way. Second, a function that calls back with several result values (callback(null, a, b)) only resolves with the first one, unless the function carries a special symbol, util.promisify.custom, that tells promisify what to do. Many built-in functions do exactly that, which is why promisify(setTimeout) resolves properly even though setTimeout's callback is not error-first. Today most core modules already ship a promise flavour (node:fs/promises, node:timers/promises, node:dns/promises), so reach for promisify for your own legacy code and for third-party callback libraries.

Methods that use this lose it when passed to promisify as a bare function. Wrap or bind first: promisify(obj.method.bind(obj)).

callbackify: the other direction

util.callbackify goes the opposite way. It is rarely needed in new code, but it is useful when you must give a callback-style API to an old library or framework while writing your own logic with async.

Node.js callbackify an async function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If the promise rejects with a falsy value (for example Promise.reject(null)), callbackify wraps it in an Error with a reason property so the callback still sees a truthy first argument. That edge case is a reason to always reject with real Error objects.

inspect: how Node prints values

When you call console.log(someObject), Node does not use toString(). It calls util.inspect, which produces a readable, safe description of any value, including circular references, Maps, Sets, class instances and typed arrays. You can call it yourself and tune it with options.

Node.js util.inspect options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The options you will use most:

Option Effect
depth How many nested levels to expand. The default is 2; null means unlimited. Deeper objects print as [Object].
compact 3 by default: up to three inner levels are combined onto one line when they fit. false puts every property on its own line.
breakLength The line width that triggers wrapping (default 80).
sorted Sort object keys, handy for stable output in tests.
showHidden Include non-enumerable properties and internal slots.
maxArrayLength, maxStringLength Truncate long arrays and strings (100 items and 10000 characters by default).
colors Wrap the output in ANSI colour codes, as the terminal does.

Because console.dir(obj, { depth: null }) is a shortcut for the same thing, you will often see that in debugging code. See Globals and the console for the other console methods.

Customising how your class prints

A class can control its own inspect output by defining a method under the symbol Symbol.for('nodejs.util.inspect.custom'), also available as util.inspect.custom. Node calls it with the depth, the options and the inspect function itself.

Node.js A custom inspect method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This is a practical safety feature: log objects that may contain secrets and your custom method decides what is visible. Without it, console.log(key) would show only the public field owner, but a plain object holding the secret would print everything. Note how the same hook runs when the object sits inside an array.

format: printf-style strings

util.format is what console.log uses when its first argument is a string. It understands a few placeholders:

Placeholder Meaning
%s String (objects without a custom toString are inspected).
%d Number (including floats; BigInt stays a bigint).
%i / %f Integer / float parsing.
%j JSON (a circular reference prints '[Circular]').
%o / %O inspect of the value (%o shows hidden details).
%c CSS, ignored in Node.
%% A literal percent sign.
Node.js util.format placeholders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Extra arguments are joined with spaces after the formatted text, and a placeholder with no matching argument is left as written. For richer layouts use template literals; format earns its place in logging helpers where you do not know the arguments in advance.

util.types and reliable type checks

typeof and instanceof are not enough in every situation. instanceof Promise fails for a promise created in another realm (a vm context or a worker), and typeof says 'object' for almost everything. util.types offers checks that look at the real internal type of the value.

Node.js util.types checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

isDeepStrictEqual(a, b) compares by value using strict rules: same types, same prototypes, own enumerable properties, NaN equal to NaN (it uses Object.is for primitives, which is why 0 and -0 differ), and sets and maps compared regardless of order. It is the engine behind assert.deepStrictEqual, covered in The assert Module. Use it when you need a boolean rather than an exception.

parseArgs: command-line arguments

process.argv is just an array of strings. Turning --name Ada -v --count=3 file.txt into something usable is boring work, so Node has util.parseArgs. It takes the arguments (by default process.argv.slice(2)) plus a description of the options you accept.

In our editor you cannot pass real command-line arguments, so we hand parseArgs an explicit args array. On your machine you would omit it.

Node.js parseArgs with options and positionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notes that save debugging time:

  • The values object has no prototype (it prints as [Object: null prototype]), so values.hasOwnProperty does not exist; use 'name' in values instead.
  • Option values arrive as strings. --count=3 gives '3'; convert with Number() yourself.
  • By default parseArgs is strict: unknown options and options that need a value but get none throw an error with a code such as ERR_PARSE_ARGS_UNKNOWN_OPTION. Pass strict: false to be lenient.
  • Positional arguments are rejected unless you set allowPositionals: true.
  • multiple: true collects repeated options into an array.
  • default fills in a value when the option is absent.

parseArgs does not print help text or support sub-commands for you. It gives you the parsed pieces; the structure is yours to build, as shown in the CLI tools lesson.

styleText: colour without a library

Terminal colours are ANSI escape sequences. util.styleText(format, text) wraps text in the right ones, accepting a style name or an array of them such as ['bold', 'red']. In recent Node versions it also checks whether the output stream supports colour and strips the codes when it does not, so piped output stays clean.

Node.js styleText and stripVTControlCharacters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The validateStream: false option forces the codes even when the stream is not a terminal, which we need here to show them. In a real CLI leave the default so that node tool.js > out.txt does not fill the file with escape codes. stripVTControlCharacters removes such codes again, for example when you want to measure the visible width of a coloured string.

deprecate: warn once, keep working

When you rename or retire a function in a library, you want old callers to keep working while learning that they should switch. util.deprecate(fn, message, code) wraps a function so that the first call prints a DeprecationWarning to stderr (once per code), and then behaves as usual.

Node.js util.deprecate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The warning goes to stderr, so your program's normal output is unaffected, and giving the warning a code lets users silence it with --no-deprecation or filter it with process.on('warning'). Use it as a polite first step before you actually remove an API.

TextEncoder and TextDecoder

util.TextEncoder and util.TextDecoder are the same classes that exist as globals in browsers and Node. They convert between strings and bytes, mainly UTF-8. We give them a full lesson in Text, Encodings and Unicode; for now, remember that new TextEncoder().encode('รฉ') gives two bytes and new TextDecoder().decode(bytes) converts back.

debuglog: logging you can switch on

util.debuglog(section) returns a logging function that does nothing unless the environment variable NODE_DEBUG contains that section name. That makes it perfect for diagnostic output in libraries: free when off, available when you need it. Node reads NODE_DEBUG when the process starts, so to show both cases in one example we run a tiny child program twice with child processes, once with the variable and once without.

Node.js debuglog sections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Debug lines go to stderr, prefixed with the section name (upper-cased) and the process id; we replace the id because it changes on every run. On your machine you would write NODE_DEBUG=cache node app.js. The fuller story of tracing and diagnostics is in Debugging and Diagnostics.

Choosing the right tool

You want to... Use
Use a callback API with await promisify, or the module's own fs/promises-style variant if it exists
Give an async function to old callback code callbackify
See a value the way console.log does, in a string inspect
Build a log message with placeholders format
Check the real type of a value, even across realms types.isXxx
Compare two structures by value isDeepStrictEqual
Read --flag value arguments parseArgs
Add colour that respects pipes styleText
Retire an API gently deprecate
Add switchable diagnostics debuglog

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does util.promisify(fn) require from fn?

    promisify expects the Node error-first convention. The callback is appended for you, a non-null err rejects the promise, and the second argument resolves it.
  2. 2. Which option makes util.inspect expand objects at every nesting level?

    The default depth is 2, and deeper levels print as [Object]. Setting depth to null removes the limit.
  3. 3. What does parseArgs do with the value of --count=3?

    Option values are strings (or booleans for flags). Convert with Number() or parseInt() yourself.
  4. 4. Why is util.types.isPromise sometimes better than instanceof Promise?

    instanceof compares against one realm's Promise constructor, while types.isPromise checks the engine's internal type.
  5. 5. How often does util.deprecate print its warning for the same code?

    The DeprecationWarning is emitted the first time a given code is used; later calls run silently.

Summary

  • node:util is a toolbox of small helpers; import it with the node: prefix.
  • promisify turns error-first callback functions into promise-returning ones, and callbackify converts back.
  • inspect is what console.log uses; control it with depth, compact, sorted and a custom util.inspect.custom method.
  • format implements %s %d %j %O placeholders.
  • util.types and isDeepStrictEqual give reliable type checks and value comparison.
  • parseArgs parses command-line options (values are strings), styleText adds colour that respects pipes.
  • deprecate warns once, and debuglog prints only when NODE_DEBUG names its section.

Next: The os and path Modules