Node.js Util Module

Node.js Util Module

The util module in Node.js provides helper functions that make it easier to work with asynchronous operations, debugging, inheritance, formatting, and more.
It is a core module, so no installation is required.


✔️ Importing the Util Module

CommonJS

const util = require('util');

ES Module

import * as util from 'node:util';

🚀 Most Useful Util Module Features


1. util.format()

Formats a string similar to printf in C.

util.format('%s:%d', 'Age', 25);
// Output: "Age:25"

Format specifiers:

  • %s – string

  • %d – number

  • %j – JSON

  • %% – percent sign


2. util.promisify()

Converts a callback-based function into a Promise-based one.

Example:

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

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

readFileAsync('test.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));


3. util.callbackify()

Converts a promise-based function into a callback-style function.

async function greet() {
return "Hello!";
}

const callbackGreet = util.callbackify(greet);

callbackGreet((err, result) => {
console.log(result); // "Hello!"
});


4. util.inherits()

Helps one constructor inherit from another (older way).

const util = require('util');

function Animal() {}
Animal.prototype.speak = function () {
console.log('Animal sound');
}

function Dog() {}
util.inherits(Dog, Animal);

const d = new Dog();
d.speak(); // Animal sound

✔️ Prefer ES6 class extends instead.


5. util.debuglog()

Creates a debug function that logs only when an environment variable is set.

const debug = util.debuglog('server');

debug('Server started');

Run with:

NODE_DEBUG=server node app.js

6. util.types

Contains type-checking functions.

Examples:

util.types.isDate(new Date()); // true
util.types.isBigInt64Array(new BigInt64Array()); // true
util.types.isPromise(Promise.resolve()); // true

7. util.inspect()

Returns a string representation of an object — useful for debugging.

const obj = { name: "Alex", age: 25 };

console.log(util.inspect(obj, { showHidden: false, depth: null }));

Useful options:

  • depth – recursion level

  • colors – colored output

  • showHidden – include non-enumerable properties


8. util.TextEncoder / util.TextDecoder

Encodes/decodes text (like browser API).

const encoder = new util.TextEncoder();
const encoded = encoder.encode("Hello");

const decoder = new util.TextDecoder();
console.log(decoder.decode(encoded)); // Hello


9. util.parseArgs()

Helps parse command line arguments (added in Node 18+).

const { parseArgs } = require('util');

const args = parseArgs({
options: {
name: { type: 'string' },
age: { type: 'string' }
}
});

console.log(args.values);


⭐ Summary Table

Feature Purpose
format() String formatting
promisify() Convert callback → Promise
callbackify() Convert Promise → callback
inherits() Set up prototype inheritance
debuglog() Conditional debug logging
types Type checking utilities
inspect() Object debugging
TextEncoder/TextDecoder Encode/decode text
parseArgs() Parse CLI arguments

You may also like...