Utility Module in Node.js
0 227
The Utility Module in Node.js is a built-in module that offers several useful functions to streamline various operations such as debugging, formatting strings, inspecting objects, and more. It comes as part of the Node.js core, so you don't need to install anything separately—just require and use it.
How to Include the Utility Module
To use the utility module in your Node.js project, simply import it using the require
function:
const util = require('util');
Commonly Used Utility Functions
1. util.format()
This function is similar to printf
in C. It allows you to format strings using placeholders.
const util = require('util');
let msg = util.format('Hello %s, you have %d unread messages.', 'John', 5);
console.log(msg); // Output: Hello John, you have 5 unread messages.
2. util.inspect()
This function returns a string representation of an object, which is useful for debugging. It can show non-enumerable properties and nested structures.
const util = require('util');
let obj = { name: 'Alice', age: 25 };
console.log(util.inspect(obj));
3. util.types
This object contains a collection of type-checking utilities. For example, you can check if a value is a TypedArray.
const util = require('util');
console.log(util.types.isTypedArray(new Uint8Array())); // true
console.log(util.types.isTypedArray([])); // false
4. util.promisify()
This function converts a callback-based function into a promise-based one, allowing you to use async/await instead of traditional callbacks.
const util = require('util');
const fs = require('fs');
const readFile = util.promisify(fs.readFile);
readFile('example.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
5. util.callbackify()
The opposite of promisify()
, this method transforms a function that returns a Promise into one that uses callbacks.
const util = require('util');
async function getData() {
return 'Data loaded';
}
const callbackFunction = util.callbackify(getData);
callbackFunction((err, result) => {
if (err) throw err;
console.log(result);
});
Conclusion
The Utility Module in Node.js is a powerful toolkit for developers. It simplifies tasks like debugging, formatting, and converting functions, making your code cleaner and more efficient. Since it's a built-in module, it requires no external installation—just plug and play!
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments