Node.js util Module Tutorial 🎯

beginner
9 min

Node.js util Module Tutorial 🎯

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. 📝

What is the util Module?

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. 💡

Installing and Importing the util Module

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:

javascript
const util = require('util');

Basic util Functions 📝

inspect()

The inspect() function is used to format and display objects in a human-readable manner. It's especially useful when debugging complex data structures.

javascript
const obj = { name: 'John', age: 25, }; console.log(util.inspect(obj)); // Output: { name: 'John', age: 25 }

isArray()

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.

javascript
console.log(util.isArray([])); // Output: true console.log(util.isArray('str')); // Output: false

Advanced util Functions 💡

promisify()

The promisify() function allows you to convert callback-based Node.js functions into Promises, making them easier to work with in asynchronous code.

javascript
const fs = require('fs'); const readFilePromise = util.promisify(fs.readFile); readFilePromise('./example.txt', 'utf8') .then((data) => { console.log(data); }) .catch((err) => { console.error(err); });

textFormat()

The textFormat() function is a more flexible version of the inspect() function, offering more formatting options for your output.

javascript
console.log(util.textFormat('Name: %s', 'John')); // Output: Name: John

Quiz 📝

Quick Quiz
Question 1 of 1

What 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! 🎯