Welcome to this comprehensive guide on the util module in Node.js! This tutorial is designed for beginners and intermediates, so let's dive right in and learn about this powerful tool in the Node.js ecosystem. 📝
The util module is a built-in Node.js module that provides a set of utility functions for various purposes. It's like a Swiss Army knife for your Node.js projects, helping you with tasks ranging from inspecting objects to creating iterators and more. 💡
Since the util module is built-in, there's no need for installation. You can import it directly into your Node.js scripts using the following syntax:
const util = require('util');The inspect() function is used to format and display objects in a human-readable manner. It's especially useful when debugging complex data structures.
const obj = {
name: 'John',
age: 25,
};
console.log(util.inspect(obj));
// Output: { name: 'John', age: 25 }The isArray() function checks if a value is an array. It returns a Boolean value: true if the value is an array and false otherwise.
console.log(util.isArray([])); // Output: true
console.log(util.isArray('str')); // Output: falseThe promisify() function allows you to convert callback-based Node.js functions into Promises, making them easier to work with in asynchronous code.
const fs = require('fs');
const readFilePromise = util.promisify(fs.readFile);
readFilePromise('./example.txt', 'utf8')
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err);
});The textFormat() function is a more flexible version of the inspect() function, offering more formatting options for your output.
console.log(util.textFormat('Name: %s', 'John'));
// Output: Name: JohnWhat is the purpose of the `inspect()` function in the `util` module?
That's it for this lesson on the util module in Node.js! With these basic and advanced functions under your belt, you're well-equipped to tackle a variety of tasks in your Node.js projects. ✅
Stay tuned for more engaging tutorials on CodeYourCraft! 🎯