util.inspect
History
numericSeparator option is supported now.maxArrayLength when inspecting Set and Map.object is from a different vm.Context now, a custom inspection function on it will not receive context-specific arguments anymore.maxStringLength option is supported now.showHidden is true.compact options default is changed to 3 and the breakLength options default is changed to 80.compact option accepts numbers for a new output mode.getters option is supported now.depth default changed back to 2.depth default changed to 20.sorted option is supported now.WeakMap and WeakSet entries can now be inspected as well.compact option is supported now.this.breakLength option is supported now.maxArrayLength option is supported now; in particular, long arrays are truncated by default.showProxy option is supported now.util.inspect(object, showHidden?, depth?, colors?): string
anyObject.Objectbooleannumberobject. This is useful for inspecting large objects. To recurse up to
the maximum call stack size pass Infinity or null.
Default: 2.booleantrue, the output is styled with ANSI color
codes. Colors are customizable. See Customizing util.inspect colors.
Default: false.booleanfalse,
[util.inspect.custom](depth, opts, inspect) functions are not invoked.
Default: true.booleanintegerArray,
TypedArray, Map, WeakMap, and WeakSet elements to include when formatting.
Set to null or Infinity to show all elements. Set to 0 or
negative to show no elements. Default: 100.integernull or Infinity to show all elements.
Set to 0 or negative to show no characters. Default: 10000.integerInfinity to format the input as a single line
(in combination with compact set to true or any number >= 1).
Default: 80.false causes each object key
to be displayed on a new line. It will break on new lines in text that is
longer than breakLength. If set to a number, the most n inner elements
are united on a single line as long as all properties fit into
breakLength. Short array elements are also grouped together. For more
information, see the example below. Default: 3.true or a function, all properties
of an object, and Set and Map entries are sorted in the resulting
string. If set to true the default sort is used. If set to a function,
it is used as a compare function.true, getters are inspected. If set
to 'get', only getters without a corresponding setter are inspected. If
set to 'set', only getters with a corresponding setter are inspected.
This might cause side effects depending on the getter function.
Default: false.booleantrue, an underscore is used to
separate every three digits in all bigints and numbers.
Default: false.stringobject.The util.inspect() method returns a string representation of object that is
intended for debugging. The output of util.inspect may change at any time
and should not be depended upon programmatically. Additional options may be
passed that alter the result.
util.inspect() will use the constructor's name and/or Symbol.toStringTag
property to make an identifiable tag for an inspected value.
class Foo { get [Symbol.toStringTag]() { return 'bar'; } } class Bar {} const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); util.inspect(new Foo()); // 'Foo [bar] {}' util.inspect(new Bar()); // 'Bar {}' util.inspect(baz); // '[foo] {}'
Circular references point to their anchor by using a reference index:
import { inspect } from 'node:util'; const obj = {}; obj.a = [obj]; obj.b = {}; obj.b.inner = obj.b; obj.b.obj = obj; console.log(inspect(obj)); // <ref *1> { // a: [ [Circular *1] ], // b: <ref *2> { inner: [Circular *2], obj: [Circular *1] } // }
const { inspect } = require('node:util'); const obj = {}; obj.a = [obj]; obj.b = {}; obj.b.inner = obj.b; obj.b.obj = obj; console.log(inspect(obj)); // <ref *1> { // a: [ [Circular *1] ], // b: <ref *2> { inner: [Circular *2], obj: [Circular *1] } // }
The following example inspects all properties of the util object:
import util from 'node:util'; console.log(util.inspect(util, { showHidden: true, depth: null }));
const util = require('node:util'); console.log(util.inspect(util, { showHidden: true, depth: null }));
The following example highlights the effect of the compact option:
import { inspect } from 'node:util'; const o = { a: [1, 2, [[ 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', 'test', 'foo']], 4], b: new Map([['za', 1], ['zb', 'test']]), }; console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); // { a: // [ 1, // 2, // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line // 'test', // 'foo' ] ], // 4 ], // b: Map(2) { 'za' => 1, 'zb' => 'test' } } // Setting `compact` to false or an integer creates more reader friendly output. console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); // { // a: [ // 1, // 2, // [ // [ // 'Lorem ipsum dolor sit amet,\n' + // 'consectetur adipiscing elit, sed do eiusmod \n' + // 'tempor incididunt ut labore et dolore magna aliqua.', // 'test', // 'foo' // ] // ], // 4 // ], // b: Map(2) { // 'za' => 1, // 'zb' => 'test' // } // } // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a // single line.
const { inspect } = require('node:util'); const o = { a: [1, 2, [[ 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', 'test', 'foo']], 4], b: new Map([['za', 1], ['zb', 'test']]), }; console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); // { a: // [ 1, // 2, // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line // 'test', // 'foo' ] ], // 4 ], // b: Map(2) { 'za' => 1, 'zb' => 'test' } } // Setting `compact` to false or an integer creates more reader friendly output. console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); // { // a: [ // 1, // 2, // [ // [ // 'Lorem ipsum dolor sit amet,\n' + // 'consectetur adipiscing elit, sed do eiusmod \n' + // 'tempor incididunt ut labore et dolore magna aliqua.', // 'test', // 'foo' // ] // ], // 4 // ], // b: Map(2) { // 'za' => 1, // 'zb' => 'test' // } // } // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a // single line.
The showHidden option allows WeakMap and WeakSet entries to be
inspected. If there are more entries than maxArrayLength, there is no
guarantee which entries are displayed. That means retrieving the same
WeakSet entries twice may result in different output. Furthermore, entries
with no remaining strong references may be garbage collected at any time.
import { inspect } from 'node:util'; const obj = { a: 1 }; const obj2 = { b: 2 }; const weakSet = new WeakSet([obj, obj2]); console.log(inspect(weakSet, { showHidden: true })); // WeakSet { { a: 1 }, { b: 2 } }
const { inspect } = require('node:util'); const obj = { a: 1 }; const obj2 = { b: 2 }; const weakSet = new WeakSet([obj, obj2]); console.log(inspect(weakSet, { showHidden: true })); // WeakSet { { a: 1 }, { b: 2 } }
The sorted option ensures that an object's property insertion order does not
impact the result of util.inspect().
import { inspect } from 'node:util'; import assert from 'node:assert'; const o1 = { b: [2, 3, 1], a: '`a` comes before `b`', c: new Set([2, 3, 1]), }; console.log(inspect(o1, { sorted: true })); // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } const o2 = { c: new Set([2, 1, 3]), a: '`a` comes before `b`', b: [2, 3, 1], }; assert.strict.equal( inspect(o1, { sorted: true }), inspect(o2, { sorted: true }), );
const { inspect } = require('node:util'); const assert = require('node:assert'); const o1 = { b: [2, 3, 1], a: '`a` comes before `b`', c: new Set([2, 3, 1]), }; console.log(inspect(o1, { sorted: true })); // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } const o2 = { c: new Set([2, 1, 3]), a: '`a` comes before `b`', b: [2, 3, 1], }; assert.strict.equal( inspect(o1, { sorted: true }), inspect(o2, { sorted: true }), );
The numericSeparator option adds an underscore every three digits to all
numbers.
import { inspect } from 'node:util'; const thousand = 1000; const million = 1000000; const bigNumber = 123456789n; const bigDecimal = 1234.12345; console.log(inspect(thousand, { numericSeparator: true })); // 1_000 console.log(inspect(million, { numericSeparator: true })); // 1_000_000 console.log(inspect(bigNumber, { numericSeparator: true })); // 123_456_789n console.log(inspect(bigDecimal, { numericSeparator: true })); // 1_234.123_45
const { inspect } = require('node:util'); const thousand = 1000; const million = 1000000; const bigNumber = 123456789n; const bigDecimal = 1234.12345; console.log(inspect(thousand, { numericSeparator: true })); // 1_000 console.log(inspect(million, { numericSeparator: true })); // 1_000_000 console.log(inspect(bigNumber, { numericSeparator: true })); // 123_456_789n console.log(inspect(bigDecimal, { numericSeparator: true })); // 1_234.123_45
util.inspect() is a synchronous method intended for debugging. Its maximum
output length is approximately 128 MiB. Inputs that result in longer output will
be truncated.
Color output (if enabled) of util.inspect is customizable globally
via the util.inspect.styles and util.inspect.colors properties.
util.inspect.styles is a map associating a style name to a color from
util.inspect.colors.
The default styles and associated colors are:
bigint:yellowboolean:yellowdate:magentamodule:underlinename: (no styling)null:boldnumber:yellowregexp: A method that colors character classes, groups, assertions, and other parts for improved readability. To customize the coloring, change thecolorsproperty. It is set to['red', 'green', 'yellow', 'cyan', 'magenta']by default and may be adjusted as needed. The array is repetitively iterated through depending on the "depth".special:cyan(e.g.,Proxies)string:greensymbol:greenundefined:grey
Color styling uses ANSI control codes that may not be supported on all
terminals. To verify color support use tty.hasColors().
Predefined control codes are listed below (grouped as "Modifiers", "Foreground colors", and "Background colors").
It is possible to define a method as style. It receives the stringified value of the input. It is invoked in case coloring is active and the type is inspected.
Example: util.inspect.styles.regexp(value)
Modifier support varies throughout different terminals. They will mostly be ignored, if not supported.
reset- Resets all (color) modifiers to their defaults- bold - Make text bold
- italic - Make text italic
- underline - Make text underlined
strikethrough- Puts a horizontal line through the center of the text (Alias:strikeThrough,crossedout,crossedOut)hidden- Prints the text, but makes it invisible (Alias: conceal)- dim - Decreased color intensity (Alias:
faint) - overlined - Make text overlined
- blink - Hides and shows the text in an interval
- inverse - Swap foreground and
background colors (Alias:
swapcolors,swapColors) - doubleunderline - Make text
double underlined (Alias:
doubleUnderline) - framed - Draw a frame around the text
blackredgreenyellowbluemagentacyanwhitegray(alias:grey,blackBright)redBrightgreenBrightyellowBrightblueBrightmagentaBrightcyanBrightwhiteBright
bgBlackbgRedbgGreenbgYellowbgBluebgMagentabgCyanbgWhitebgGray(alias:bgGrey,bgBlackBright)bgRedBrightbgGreenBrightbgYellowBrightbgBlueBrightbgMagentaBrightbgCyanBrightbgWhiteBright
Custom inspection functions on objects
History
Objects may also define their own
[util.inspect.custom](depth, opts, inspect) function,
which util.inspect() will invoke and use the result of when inspecting
the object.
import { inspect } from 'node:util'; class Box { constructor(value) { this.value = value; } [inspect.custom](depth, options, inspect) { if (depth < 0) { return options.stylize('[Box]', 'special'); } const newOptions = Object.assign({}, options, { depth: options.depth === null ? null : options.depth - 1, }); // Five space padding because that's the size of "Box< ". const padding = ' '.repeat(5); const inner = inspect(this.value, newOptions) .replace(/\n/g, `\n${padding}`); return `${options.stylize('Box', 'special')}< ${inner} >`; } } const box = new Box(true); console.log(inspect(box)); // "Box< true >"
const { inspect } = require('node:util'); class Box { constructor(value) { this.value = value; } [inspect.custom](depth, options, inspect) { if (depth < 0) { return options.stylize('[Box]', 'special'); } const newOptions = Object.assign({}, options, { depth: options.depth === null ? null : options.depth - 1, }); // Five space padding because that's the size of "Box< ". const padding = ' '.repeat(5); const inner = inspect(this.value, newOptions) .replace(/\n/g, `\n${padding}`); return `${options.stylize('Box', 'special')}< ${inner} >`; } } const box = new Box(true); console.log(inspect(box)); // "Box< true >"
Custom [util.inspect.custom](depth, opts, inspect) functions typically return
a string but may return a value of any type that will be formatted accordingly
by util.inspect().
import { inspect } from 'node:util'; const obj = { foo: 'this will not show up in the inspect() output' }; obj[inspect.custom] = (depth) => { return { bar: 'baz' }; }; console.log(inspect(obj)); // "{ bar: 'baz' }"
const { inspect } = require('node:util'); const obj = { foo: 'this will not show up in the inspect() output' }; obj[inspect.custom] = (depth) => { return { bar: 'baz' }; }; console.log(inspect(obj)); // "{ bar: 'baz' }"
symbolIn addition to being accessible through util.inspect.custom, this
symbol is registered globally and can be
accessed in any environment as Symbol.for('nodejs.util.inspect.custom').
Using this allows code to be written in a portable fashion, so that the custom
inspect function is used in a Node.js environment and ignored in the browser.
The util.inspect() function itself is passed as third argument to the custom
inspect function to allow further portability.
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom'); class Password { constructor(value) { this.value = value; } toString() { return 'xxxxxxxx'; } [customInspectSymbol](depth, inspectOptions, inspect) { return `Password <${this.toString()}>`; } } const password = new Password('r0sebud'); console.log(password); // Prints Password <xxxxxxxx>
See Custom inspection functions on Objects for more details.
The defaultOptions value allows customization of the default options used by
util.inspect. This is useful for functions like console.log or
util.format which implicitly call into util.inspect. It shall be set to an
object containing one or more valid util.inspect() options. Setting
option properties directly is also supported.
import { inspect } from 'node:util'; const arr = Array(156).fill(0); console.log(arr); // Logs the truncated array inspect.defaultOptions.maxArrayLength = null; console.log(arr); // logs the full array
const { inspect } = require('node:util'); const arr = Array(156).fill(0); console.log(arr); // Logs the truncated array inspect.defaultOptions.maxArrayLength = null; console.log(arr); // logs the full array