Often, especially when debugging, you need to convert a JavaScript object into a string representation. The util.inspect()
method allows you to inspect an object and then return a string representation of the object.
The following is the syntax for the inspect()
method:
util.inspect(object, [options])
The object
parameter is the JavaScript object you want to convert to a string. The options
method allows you to control certain aspects of the formatting process. options
can contain the following properties:
showHidden: When set to true
, the non-enumerable properties of the object are also converted into the string. Defaults to false
.
depth: Limits the number of levels deep the inspect process traverses while formatting properties that are also objects. This can prevent infinite loops and also prevent complex objects from costing a lot of CPU cycles. Defaults to 2
; if it is null
, it can recurse forever.
colors: When set to true
, the output is styled with ANSI color codes. Defaults to false
.
customInspect: When set to false
, any custom inspect()
functions defined on the objects being inspected are not called. Defaults to true
.
You can attach your own inspect()
function to an object in order to control the output. The following code creates an object with first
and last
properties, and inspect()
outputs only a name
property:
var obj = { first:'Brad', last:'Dayley' };
obj.inspect = function(depth) {
return '{ name: "' + this.first + " " + this.last + '" }';
};
console.log(util.inspect(obj));
// { name: "Brad Dayley" }