What is the util module's inspect() function used for, and how does it relate to how console.log() displays objects?
Short answer
util.inspect() converts a value into a formatted, human-readable string, including nested objects -- it's what console.log() uses internally (rather than JSON.stringify, which can't handle circular references or non-JSON types), and can be called directly for custom formatting…
Advertisement
AModel answer
util.inspect() converts a value into a formatted, human-readable string, including nested objects -- it's what console.log() uses internally (rather than JSON.stringify, which can't handle circular references or non-JSON types), and can be called directly for custom formatting needs like controlling nesting depth.
const obj = { name: 'Alice', nested: { deep: { value: 42 } } };
console.log(util.inspect(obj, { depth: 1, colors: true }));Real-world example
A logging utility uses util.inspect() with a bounded depth to safely log deeply nested request objects without crashing on a circular reference, which JSON.stringify would throw on.
Likely follow-ups
- Why does JSON.stringify() throw on a circular reference while console.log() handles it gracefully?
- How would you define a custom inspection format using util.inspect.custom?
Related topics