Loading lesson path
Concept visual
Start at both ends
The Util module is a core Node.js module that provides a collection of utility functions for common tasks. It's like a Swiss Army knife for Node.js developers, offering solutions for:
Consistent with Node.js core
While some functions in the Util module are designed for internal use by Node.js itself, many are valuable tools for developers building Node.js applications. The module is included with Node.js, so no installation is required.
Here's a practical example that demonstrates several utilities from the Util module in action:
const util = require('util');
const fs = require('fs');
// Convert callback-based fs.readFile to Promise-based const readFile = util.promisify(fs.readFile);
// Format strings with placeholders const greeting = util.format('Hello, %s! Today is %s', 'Developer', new Date().toDateString());
console.log(greeting);
// Inspect an object with custom options const obj = {
name: 'Test', nested: { a: 1, b: [2, 3] }, fn: function() { return 'test'; }
};
console.log(util.inspect(obj, { colors: true, depth: 2 }));
// Use debug logging const debug = util.debuglog('app');
debug('This will only show if NODE_DEBUG=app');
// Example of using promisify with async/await async function readConfig() {
try {
const data = await readFile('package.json', 'utf8');
console.log('Package name:', JSON.parse(data).name);
} catch (err) {
console.error('Error reading config:', err);
}
}
readConfig();The Util module can be imported in several ways depending on your module system and needs: CommonJS (Node.js default)
// Import the entire module const util = require('util');
// Import specific functions using destructuring const { promisify, inspect, format } = require('util');
// Using strict mode (recommended)
const assert = require('assert').strict;// For TypeScript users
// import * as util from 'util';
// import { promisify, inspect } from 'util';
ES Modules (Node.js 12+)
// Default import import util from 'util';
// Named imports import { promisify, inspect } from 'util';
// Rename imports import { promisify as pify } from 'util';
// Dynamic import (Node.js 14+)
const { promisify } = await import('util');// Using with TypeScript types
// import * as util from 'util';
// import type { InspectOptions } from 'util';Formula
For better tree - shaking and smaller bundles, prefer destructuring imports of only the functions you need.The Util module is quite large, and you typically only use a small subset of its functionality.
The Util module provides powerful tools for formatting strings and inspecting objects, which are particularly useful for logging and debugging. util.format(format[, ...args])
Formula
Returns a formatted string using the first argument as a printf - like format string.This is similar to console.log()but returns the formatted string instead of printing it.
%s - String %d - Number (both integer and float) %i - Integer %f - Floating point value %j - JSON (replaced with '[Circular]' if the argument contains circular references) %o - Object (inspect the object) %O - Object (inspect the object, with full detail) %% - Single percent sign ('%')
const util = require('util');
// Basic formatting const formatted = util.format('Hello, %s!', 'World');
console.log(formatted); // 'Hello, World!'
// Multiple placeholders const multiFormatted = util.format(
'My name is %s. I am %d years old and I love %s.',
'Kai',30, 'Node.js'
);
console.log(multiFormatted);
// 'My name is Kai. I am 30 years old and I love Node.js.'
// Available specifiers const specifiers = util.format(
'String: %s, Number: %d, JSON: %j, Character: %c',
'hello',42,
{ name: 'Object' },
65 // ASCII code for 'A'
);
console.log(specifiers);
// Extra arguments are concatenated with spaces const extra = util.format('Hello', 'World', 'from', 'Node.js');
console.log(extra); // 'Hello World from Node.js'
util.inspect(object[, options])Returns a string representation of an object, useful for debugging. This is what Node.js uses internally for printing objects to the console.