A Few Useful Functions in Node.js Util Module

A Few Useful Functions in Node.js Util Module

Daily short news for you
  • A software that converts text to speech created by a Vietnamese programmer - J2TEAM - Text to Speech (Free). You can convert dozens of languages into dozens of different natural voices. The special thing is that it is free.

    In preliminary evaluation, the conversion of long texts or texts in pure Vietnamese is very good. However, when it includes English words, it sounds a bit funny 😅

    » Read more
  • How terrifying, Codeium - known as a competitor to Github Copilot, as it allows users to use it for free without limits. Recently, they introduced the Windsurf Editor - no longer just a VSCode Extension but a full Editor now - directly competing with Cursor. And the main point is that it... is completely free 🫣.

    » Read more
  • There is a rather interesting study that I came across: "Users never bother to read things they don't want to." (That's a bold statement, but it's more true than not. 😅)

    Don't believe it? I bet you've encountered situations where you've clicked on a button repeatedly and it doesn't respond, but in reality, it has displayed an error message somewhere. Or you've filled out everything and then when you hit the submit button, it doesn't go through. Frustrated, you scroll up or down to read and find out... oh, it turns out there's an extra step or two you need to take, right?

    It’s not far from the blog here. I thought that anyone who cares about the blog would click on the "Allow notifications" button just below the post. But the truth is, no one bothers to click it. Is it because they don't want to receive notifications? Probably not! I think it's because they just didn’t read that line.

    The evidence is that only when a notification pops up and takes up half the screen, or suddenly appears to grab attention, do they actually read it—and of course, it attracts a few more subscribers—something that was never achieved before.

    » Read more

The Issue

Node.js encompasses a range of components that come together to form a JavaScript runtime environment. In our series on Node.js Architecture - Introduction to Node.js, we explored the various components that make up Node.js and their respective functions.

Within Node.js, there are numerous built-in modules - i.e., modules that are integrated from the outset. One such module is util, which, in my opinion, deserves more attention. The util module comprises a collection of small utility functions that can be helpful in certain situations. In this article, we will delve into some of these functions...

util.promisify and util.callbackify

The callback is one of the earliest ways to handle asynchronous code. However, callbacks have several limitations, such as creating nested code and causing the infamous "callback hell." Occasionally, reading a piece of code written in a callback style can be overwhelming. Adding new functionality can be challenging, as it requires introducing an additional layer of logic.

In Node.js, there is a utility function to convert asynchronous functions using the callback style to Promises. This function is useful when you want to transition to a Promise-based approach and then combine it with async/await to make your code more concise and easier to follow.

const util = require('node:util');
const fs = require('node:fs');

const stat = util.promisify(fs.stat);

async function callStat() {
  const stats = await stat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}

callStat(); 

Conversely, we have util.callbackify to convert Promise-based functions back to callbacks.

const util = require('node:util');

async function fn() {
  return 'hello world';
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
}); 

util.deprecate

If you frequently use libraries, you may have noticed console messages indicating that a function is deprecated.

oldFunction() is deprecated. Use newFunction() instead.

This is a notification that the oldFunction is nearing the end of its support lifecycle and may be removed in the future. It is a common approach to remind developers that a function is approaching its "retirement" and to use an alternative function instead.

In Node.js, there is a simple way to display this notification if you need to warn others that a function is nearing its end-of-life.

const util = require('util');

function oldFunction() {
    console.log('This function is deprecated!');
}

const deprecatedFunction = util.deprecate(oldFunction, 'oldFunction() is deprecated. Use newFunction() instead.');

Simply "wrap" the oldFunction inside util.deprecate. Each time oldFunction is called, the warning message will appear in the console.

util.types

From ES6 onward, we have additional functions to check the type of data: boolean, array, object, etc.

The util module has a types property that extends the capability to check data types.

For instance:

console.log(util.types.isPromise(Promise.resolve())); // true
console.log(util.types.isRegExp(/abc/)); // true
console.log(util.types.isDate(new Date())); // true

A comprehensive list is available at util.types | Node.js documentation.

util.isDeepStrictEqual

isDeepStrictEqual is the most efficient method to compare two objects and determine if they are identical.

const util = require('util');

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { a: 1, b: { c: 2 } };

console.log(util.isDeepStrictEqual(obj1, obj2)); // true

In addition to these functions, the util module provides many other utility functions, such as util.styleText to format text output in the console, and util.parseEnv to parse the contents of environment variables in .env files.

For more information, refer to:

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (0)

Leave a comment...