Cedric, you are correct that I wasn't returning anything from inspect -- the peril of trying to write code at 4am! But I can't seem to get rid of using self=this
because it seems like I have to keep attaching the inspect function to the inner objects. After further experimentation, I have ended up with something that does not quite format things exactly the way util.inspect does, but it's close enough for my purposes.
var util=require('util');
var a = {a:'a', b:'b', c:[1,2,3], d:{ d1:{ d2: { d3:[1,2,3] }}, dd1: { dd2: { dd3: [1,2,3]}}}};
a.inspect = function(depth){
var self = this;
var sp = ' ';
return '{ ' + Object.keys(self).reduce( function(str,key){
if( key==='inspect' && typeof self[key]==='function' ) return str ;
if(Array.isArray(self[key])){
return str+(str?',\n'+sp.repeat(depth+1):'')+key+': Array['+self[key].length+']';
}else{
if( typeof self[key] === 'object' ) self[key].inspect=a.inspect ;
return str+(str?',\n'+sp.repeat(depth+1):'')+key+': '+util.inspect(self[key], {colors:true,depth:null});
}
}, '') + ' }'
};
console.log( util.inspect( a, {colors:true,depth:null} ));
This requires a version of node that supports the repeat method, otherwise see MDN for a polyfill. Here is the output:
{ a: 'a',
b: 'b',
c: Array[3],
d: { d1: { d2: { d3: Array[3] } },
dd1: { dd2: { dd3: Array[3] } } } }