keepcalculator

06 Numbers and Powers

Node.js util Module: Key Functions & Usage

Card No. 06·53948 · Updated · Standard formula, shown below

The Node.js util module provides a set of utility functions that support internal Node.js APIs and are also useful for everyday application development. You can access it with const util = require('util') and use it for type checking, formatting, callbacks, and debugging.

Background: Why a util Module?

Node.js has a small standard library, but it includes a util module that has grown over time. Originally, it was mainly for internal use by Node.js itself, but it became public because many of its functions were useful for developers. The module provides helpers for:

  • Formatting strings (like printf in C).
  • Converting callback-based functions to promises.
  • Inspecting objects for debugging.
  • Checking types (including built-in objects like Date and RegExp).
  • Inheriting from constructors (older style).

Because Node.js is open-source, the module’s evolution reflects real needs. For example, util.promisify was added when promises became popular, and util.types was added to help identify objects created from different realms (like vm contexts).

Key Functions and How to Use Them

The most commonly used functions in the util module are:

  • util.format(format, ...args) – returns a formatted string using %s, %d, %j, and %% placeholders. For example, util.format('%s is %d years old', 'Alice', 30) returns 'Alice is 30 years old'.
  • util.inspect(object, options) – returns a string representation of an object, useful for debugging. Options include showHidden, depth, and colors.
  • util.promisify(fn) – takes a function that follows the Node.js callback style (error-first) and returns a promise-based version. For example, const readFile = util.promisify(fs.readFile).
  • util.callbackify(fn) – the reverse: converts a promise-returning function to a callback-style function.
  • util.types – a set of functions like util.types.isDate(), util.types.isRegExp(), util.types.isPromise(), and util.types.isArrayBuffer().
  • util.isDeepStrictEqual(val1, val2) – checks deep equality (similar to assert.deepStrictEqual but returns a boolean).

For example, to check if a value is a Date:

const util = require('util');
const d = new Date();
console.log(util.types.isDate(d)); // true

How to Choose Between util and Other Methods

Sometimes you can use native JavaScript instead of util. For basic type checks, typeof and Array.isArray() are sufficient. For deep equality, you might use assert.deepStrictEqual (which throws) or JSON.stringify (which has limitations). util.isDeepStrictEqual is a good choice when you need a boolean result without throwing.

For formatting, template literals or libraries like sprintf-js can work, but util.format is built-in and lightweight. For converting callbacks to promises, util.promisify is standard, but if you use modern fs.promises API, you don’t need it.

Generally, use util when you need a well-tested, built-in solution and don’t want to add dependencies.

Common Problems and Misconceptions

One common mistake is using typeof to check for null or arrays. typeof null returns "object", and typeof [] also returns "object". Use util.types.isAnyArrayBuffer() or Array.isArray() instead.

Another issue is forgetting that util.promisify only works with functions that follow the exact callback signature: (err, value) as the last arguments. If the callback receives multiple success values, promisify will only resolve with the first one. You can customize this with a symbol like util.promisify.custom.

Also, util.inspect can produce circular references if you don’t set depth to null or a high number. For example, util.inspect(obj, { depth: null }) will fully expand nested objects.

Alternatives and Comparisons

There are third-party libraries that overlap with util:

  • lodash provides _.isEqual for deep equality, which is similar to util.isDeepStrictEqual but with different semantics (e.g., it doesn’t distinguish NaN the same way).
  • chalk for colored output, but util.inspect with colors: true can do basic coloring.
  • bluebird has Promise.promisify, but util.promisify is built-in and doesn’t require a promise library.

In most cases, the built-in util module is sufficient and avoids extra dependencies. However, for complex deep equality with custom types, lodash might be more flexible.

Safety and Best Practices

There are no direct safety concerns with the util module, but there are best practices:

  • Use util.promisify carefully with functions that may throw synchronously; wrap them in try/catch.
  • When using util.inspect on large objects, limit depth and maxArrayLength to avoid performance issues.
  • For type checking, prefer util.types over instanceof when dealing with objects from different realms (e.g., from vm or iframes).
  • Always require the module with const util = require('util'); do not use require('util').promisify repeatedly.

Also, note that some functions like util.inherits are legacy; use ES6 classes instead.

Frequently Asked Questions

What is the difference between util.promisify and using async/await?

util.promisify converts a callback-based function to a promise-returning function, which you can then use with async/await. It doesn’t replace async/await; it makes older APIs compatible with modern promise syntax.

Can I use util.format in the browser?

No, util is a Node.js core module and is not available in browsers. However, you can use console.log with template literals or a library like sprintf-js for similar formatting.

How do I check if a value is a Promise using util?

Use util.types.isPromise(value). This works even for promises from other realms, which instanceof Promise might miss.

Is util.isDeepStrictEqual the same as lodash’s isEqual?

Not exactly. util.isDeepStrictEqual follows strict equality semantics (e.g., NaN is considered equal to NaN), while lodash’s isEqual treats NaN as equal too, but there are differences in how they handle typed arrays and prototypes.

Can I use util.inherits in modern Node.js?

Yes, it still works, but it’s deprecated in favor of ES6 class and extends. It’s recommended to use classes for new code.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →