devnotes.

The Utility (util) Module

util is a grab bag of small, genuinely handy functions Node.js provides for tasks that come up constantly but aren't big enough to deserve their own module. Two of its exports in particular are worth knowing well.

util.format() — string formatting with placeholders

const util = require('util');

const message = util.format('User %s placed order #%d for $%s', 'Fatima', 2048, '89.99');
console.log(message);
// User Fatima placed order #2048 for $89.99

%s substitutes a string, %d a number, %j a JSON-stringified value, and %o a generic object. It's essentially a lighter-weight alternative to template literals when you're building formatted strings from a fixed pattern plus variable data — common in structured logging.

util.inspect() — turning any value into a readable string

const deepObject = {
  user: { id: 1, name: 'Fatima' },
  orders: [{ id: 101, total: 89.99 }],
  createdAt: new Date()
};

console.log(util.inspect(deepObject, { depth: null, colors: true }));

This is actually what console.log() uses internally to display objects — calling it yourself gives you control over depth (how many levels deep to expand nested objects, null meaning unlimited) and colors (syntax-highlighted output in supporting terminals).

util.promisify() — converting an old-style callback function into a Promise-based one

Many older Node.js APIs and libraries still follow the error-first callback pattern. promisify wraps one of these into a function that returns a Promise instead, so it can be used with async/await:

const fs = require('fs');
const util = require('util');

const readFileAsync = util.promisify(fs.readFile);

async function loadConfig() {
  try {
    const data = await readFileAsync('config.json', 'utf8');
    console.log(JSON.parse(data));
  } catch (error) {
    console.error('Could not load config:', error.message);
  }
}

loadConfig();

(In modern Node.js, fs.promises.readFile already exists and is generally preferred for this specific case — but util.promisify remains valuable for any other callback-based function, including ones from third-party libraries or your own older code, that doesn't already have a Promise version.)

util.types — checking exactly what kind of value something is

console.log(util.types.isPromise(Promise.resolve())); // true
console.log(util.types.isDate(new Date()));            // true
console.log(util.types.isRegExp(/abc/));                // true

More precise than typeof for distinguishing specific built-in object types, which typeof generally just lumps together as 'object'.

The practical takeaway

util isn't something you'll reach for daily, but promisify in particular is worth remembering — it's the cleanest bridge between older callback-based code and modern async/await syntax, without needing to manually rewrap every function by hand.

The Utility (util) Module | DevNotes