The Util module provides a variety of utility functions that handle common tasks. It is considered a "catch-all" module for helpful functions that don't quite fit into their own dedicated core modules.
One of its most famous and widely used features is the ability to convert old callback-based functions into modern Promises!
Before async/await and Promises became standard in JavaScript, asynchronous code heavily relied on "callbacks." To modernize old callback code, you can use util.promisify().
const util = require('util');
const fs = require('fs');
// Convert the old callback-based fs.readFile into a Promise
const readFilePromise = util.promisify(fs.readFile);
async function getFileData() {
try {
// Now we can use modern async/await syntax!
const data = await readFilePromise(__filename, 'utf8');
console.log('First line of this file:', data.split('\n')[0]);
} catch (err) {
console.error('Failed to read file:', err.message);
}
}
getFileData();
The util.format() method works similarly to printf in C. It allows you to format strings using placeholders like %s for strings and %d for numbers.
const util = require('util');
const formattedStr = util.format('Hello %s! You have %d new messages.', 'Alice', 5);
console.log(formattedStr);
// Outputs: Hello Alice! You have 5 new messages.
What is the purpose of `util.promisify()`?