Hello everyone, today we are going to learn about the util module, a frequently used node.js core module. We will learn about what it is, why it is useful, and how to use it in node.js application development. We will also learn about inheritance in the Node.js JavaScript ecosystem. Let’s start.

Util Module

This lesson and the coming one will cover some of the modules that we generally use in development. One of the modules is util and it comes very handy to ease the developer work while debugging. Let’s talk more about it by answering the following questions.

What is the util module and why we use it?

It’s a Nodejs core module that provides helpful utility functions. This module helps us in debugging with a set of functions that helps us in tasks like string formatting, debugging, type checking, etc. It can be required in any file using:

const util = require('util');

A common task like console logging can become troublesome when we try to print an object that has a link to itself. Util module provides a solution to such a problem by its utility function inspect.

util.inspect(object) formats the string beautifully making our job easier. There are a lot of such cases where util modules save the day, we will learn about them in the next section.

Utility functions provided by Util Module

Now, we are going through some of the commonly used utility functions and learn their benefits.

1. util.inspect

As the name suggests, this function is used to inspect any javascript object. It takes an object as the first argument and options as the second argument. Then it returns a string representation of the object for debugging purpose. This also works for circular reference where an object has a link to itself. Example:

const util = require('util');  

const obj = {
  a: 5,
  b: 6,
};
obj.self = obj;

console.log(util.inspect(obj));

// prints { a: 5, b: 6, self: [Circular] }

We can see it also mentions that we have a circular dependency which will be very helpful in debugging.

The options paramenter takes an object with bunch of property. Some of the properties are showHidden, depth, colors, sorted, etc. You can learn about them in the documentation.

#node #javascript #programming #developer

Node.js Lesson 6: Util and Inheritance
1.90 GEEK