CodeBlanks Logo Icon CodeBlanks

util.inspect

Learn to inspect objects with util.inspect.

util.inspect

util.inspect(object) returns a string representation of an object. It formats like console.log but returns a string; you can write it to a file or append to a log.

Import: const util = require("node:util");. Example: util.inspect({ a: 1, b: [2, 3] }) gives { a: 1, b: [ 2, 3 ] }. The options object is the second parameter: { depth: 2, colors: true, compact: false }. depth controls how many nested levels are shown; null means infinite depth. colors enables colored output (if the terminal supports it). compact decides single-line or multi-line output.

Options and output

The options of util.inspect format output flexibly. colors: true shows keys green and strings yellow in the terminal; false gives plain text. compact: false writes each property on a new line; true squeezes onto one line.

Example: util.inspect({ a: 1, b: 2 }, { compact: false }) gives {\n a: 1,\n b: 2\n}. breakLength sets how many characters before a line breaks; Infinity never breaks. These options keep large objects readable. If you do not need colors, write colors: false; when writing to a file, do this so color codes do not break. The output is always deterministic; the same object gives the same string.

Practice Print an object with inspect

Import with const util = require("node:util");. Define const obj = { name: "Ayşe", age: 30, hobbies: ["music", "book"] };. Print with console.log(util.inspect(obj, { depth: 2, colors: false })). Add console.log("Inspection done").

Starter code

index.js
// Import util
// write here

// Define the obj object
// write here

// Print with inspect
// write here

// Print "Inspection done"
// write here

Sample solution

index.js
const util = require("node:util");
const obj = { name: "Ayşe", age: 30, hobbies: ["music", "book"] };
console.log(util.inspect(obj, { depth: 2, colors: false }));
console.log("Inspection done");

Expected output

{ ad: 'Ayşe', yas: 30, ilgi: [ 'müzik', 'kitap' ] }
İnceleme tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does depth: 2 control?

index.js
util.inspect(obj, { depth: 2 })
  • How many objects are printed
  • How many nested levels are shown Correct answer
  • How many lines the output has
  • The number of colors

Explanation: depth limits nested levels shown.

2 Match each option to its function

Term Meaning
depth Nested level count
colors Colored output
compact Single-line or multi-line
breakLength Line break threshold

3 Complete the inspect call

Question
const result = util.____(obj, { depth: 2 });
Answer
const result = util.inspect(obj, { depth: 2 });

Explanation: util.inspect turns an object into a string.

All lessons in Intermediate