Open In App

Node.js util.inspect() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them by ‘require(‘util’)’.

The util.inspect() (Added in v0.3.0) method is an inbuilt application programming interface of the util module which is intended for debugging and returns a string representation of the object. The util.inspect() method is not programmatically dependent. It returns output that may change any time to alter the result supplementary options (like showHidden, depth) could be passed. For inspected value, it either uses the constructor name or @@toStringTag to make an identifiable tag.

Syntax:

const util = require('util');
util.inspect(object[, options])

Parameters: This function accepts two parameters as mentioned above and described below:

  • object <any>: Any Class, Function, Object, or JavaScript primitive.

  • options <Object>: The options are of ‘object’ type which accepts the JSON form of the data.

    • showHidden <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then it starts showing hidden non-enumerable symbols and properties along with user-defined prototype, WeakMap and WeakSet entries in the formatted result.
    • depth <number>: By default, the value of the object is set ‘2’. It specifies how many times to recurse and while inspecting large objects and call stack size is passed Infinity or null to recurse up to the maximum.
    • colors <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then output gets colored style with ANSI color codes.
    • customInspect <boolean>: By default, the value of the object is set ‘true’, if it is set ‘false’ then, [[util.inspect.custom](depth, opts)] functions are not invoked.
    • showProxy <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then the target and handler objects are included by the proxy inspection.
    • maxArrayLength <integer>: By default, the value of the object is set ‘100’. While formatting maximum length is specified, i.e. how many Arrays, WeakMaps, and WeakSets are needed to be included in the formatted result. To show (0) no elements, set the value to 0 or negative and to show all elements, set the value to Infinity or null.
    • maxStringLength <integer>:  By default, the value of the object is set ‘Infinity’. While formatting the maximum length of characters is specified, i.e. length of characters to be included in the formatted result. To show (”) no characters, set the value to 0 or negative and to show all elements, set the value to Infinity or null.
    • breakLength <integer>: By default, the value of the object is set ’80’. While formatting it specifies the maximum length at which input values are split across multiple lines. To format the input in a single line, set it to Infinity.
    • sorted <boolean> | <Function>: By default, the value of the object is set ‘false’, if it is set ‘true’ or a function is passed, all properties are sorted in the formatted string. Default sort is used if set to ‘true’ and it is used as a compare function if set to a function.
    • getters <boolean> | <string>: By default, the value of the object is set ‘false’, if it is set to ‘true’ then getters will be inspected. If it is set to ‘get’ then only getters will be inspected. If it is set to ‘set’ then only getters with a corresponding setter will be inspected. This risk of side effects is high depending on the getter function.

Return Value: <string>: Returns the formatted string which represents the object.

Example 1: Filename: index.js




// Node.js syntax to demonstrate
// the util.inspect() method 
  
// Importing util library
const util = require('util');
  
// Object
const nestedObject = {};
nestedObject.a = [nestedObject];
nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];
nestedObject.b = {};
nestedObject.b.inner = nestedObject.b;
nestedObject.b.obj = nestedObject;
  
// Inspect by basic method
console.log("1.>", util.inspect(nestedObject));
  
// Random class 
class geeksForGeeks { }
  
// Inspecting geeksForGeeks class 
console.log("2.>", util.inspect(new geeksForGeeks()));
  
// Inspect by passing options to method
console.log("3.>", util.inspect(
        nestedObject, true, 0, false));
  
// Inspect by calling option name
console.log("4.>", util.inspect(nestedObject,
    showHidden = false, depth = 0, colorize = true));
  
// Inspect by passing in JSON format 
console.log("5.>", util.inspect(nestedObject,
    { showHidden: false, depth: 0, colorize: true }));
  
// Inspect by directly calling inspect from 'util'
const { inspect } = require('util');
  
// Directly calling inspect method
// with single property
console.log("6.>", inspect(nestedObject),
        { colorize: true });
  
// Directly passing the JSON data
console.log("7.>", util.inspect([
    { name: "Amit", city: "Ayodhya" },
    { name: "Satyam", city: "Lucknow" },
    { name: "Sahai", city: "Lucknow" }],
    false, 3, true));
  
// Directly calling inspect method with single property
console.log("8.>", inspect(nestedObject), { depth: 0 });


Run index.js file using the following command:

node index.js

Output:

1.> <ref *1> {
  a: [ [Circular *1] ],
  b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
}
2.> geeksForGeeks {}
3.> { a: [Array], b: [Object] }
4.> { a: [Array], b: [Object] }
5.> { a: [Array], b: [Object] }
6.> <ref *1> {
  a: [ [Circular *1] ],
  b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
} { colorize: true }
7.> [
  { name: 'Amit', city: 'Ayodhya' },
  { name: 'Satyam', city: 'Lucknow' },
  { name: 'Sahai', city: 'Lucknow' }
]
8.> <ref *1> {
  a: [ [Circular *1] ],
  b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
} { depth: 0 }

Example 2: Filename: index.js




// Node.js syntax to demonstrate the 
// util.inspect() method 
  
// Import the util module 
const util = require('util');
const { inspect } = require('util');
  
// Importing http module
var http = require('http');
  
// Inspecting http module
console.log("1.>", util.inspect(http, {
    showHidden: false,
    depth: 0, showProxy: false
}));
  
// Inspecting console module
console.log("2.>", util.inspect(
    console, showHidden = false,
    depth = 0, showProxy = true));
  
// Creating array filled with default value 1
const inspectArray = Array(108).fill(1);
  
// Prints the truncated array
console.log("3.>", inspectArray);
util.inspect.defaultOptions.maxArrayLength = null;
  
// Prints the full array
console.log("4.>", inspectArray);
  
const object = {
    amit: [1, 2, [[
        'alfa_romeo, spp___, sahai_harshit ' +
        'Annapurna, chai paratha.',
        'chota',
        'bong']], 55],
    vikas: new Map([
        ['alfa', 1], ['romeo', 'data']])
};
  
// Returns the compact view output.
console.log("5.>", util.inspect(object, {
    compact: true, depth: 5,
    breakLength: 80
}));
  
// Returns the output more reader friendly.
console.log("6.>", util.inspect(object, {
    compact: false, depth: 5,
    breakLength: 80
}));
  
const object1 = { alfa: 10 };
const object2 = { beta: 20 };
  
// Creating weakSet
const inspectingWeakset = 
    new WeakSet([object1, object2]);
  
console.log("7.>", inspect(
    inspectingWeakset, { showHidden: true }));
// Output { { alfa: 10 }, { beta: 20 } }
  
object2[util.inspect.custom] = (depth) => {
    return { alfaa: 'romeo' };
};
  
console.log("8.>", util.inspect(object2));
// Prints: "{ alfaa: 'romeo' }"


Run index.js file using the following command:

node index.js

Output:

1.> { _connectionListener: [Function: connectionListener], …. globalAgent: [Getter/Setter]}
2.> { log: [Function: bound consoleCall], …..[Symbol(kFormatForStderr)]: [Function: bound ]}
3.> [ 1, 1, 1, 1, 1, 1, ………1, 1, 1, 1, 1, … 8 more items]
4.> [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ….1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
5.> { amit: [ 1, 2, [ [ ‘alfa_romeo, spp___, sahai_harshit Annapurna, chai paratha.’,
‘chota’, ‘bong’ ] ], 55 ], vikas: Map(2) { ‘alfa’ => 1, ‘romeo’ => ‘data’ } }
6.> returns the output more reader friendly.
7.> WeakSet { { alfa: 10 }, { beta: 20 } }
8.> { alfaa: ‘romeo’ }

The util.format(format[, …])  method also gives the same result along with formatted string using the first argument as a printf-like format.

Reference: https://nodejs.org/api/util.html#util_util_inspect_object_options



Last Updated : 28 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads