Node.js
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.
Exercise 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").
Show example solution
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");
Test yourself
-
What does depth: 2 control?
util.inspect(obj, { depth: 2 })
- How many objects are printed
- How many nested levels are shown
- How many lines the output has
- The number of colors
Show answer
How many nested levels are shown — depth limits nested levels shown.
-
Match each option to its function
- depth
- Nested level count
- colors
- Colored output
- compact
- Single-line or multi-line
- breakLength
- Line break threshold
-
Complete the inspect call
const result = util.____(obj, { depth: 2 });
Show answer
const result = util.inspect(obj, { depth: 2 });
Next lesson: Source maps