Richard Richard - 18 days ago 8
Node.js Question

What method do I need to define to implement inspect function in nodejs/v8

I have a C++ class integrated into NodeJS, I would like to change its default object printing

example:

var X = new mypkg.Thing() ;
console.log( X ) ; // prints the object in std way
console.log( X.toString() ) ; // prints Diddle aye day
console.log( '' + X ) ; // prints Diddle aye day


I have defined ToString in the external code, that works. But I want the default printing to be the same.

void WrappedThing::ToString( const v8::FunctionCallbackInfo<v8::Value>& args ) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set( String::NewFromUtf8( isolate, "Diddle aye day") );
}


Is there an 'Inspect' method to override?

TIA

Answer

There is a section on this in the node.js util documentation. Basically you can either expose an inspect() method on the object/class or set the function via the special util.inspect.custom symbol on the object.

Here is one example using the special symbol:

const util = require('util');

const obj = { foo: 'this will not show up in the inspect() output' };
obj[util.inspect.custom] = function(depth, options) {
  return { bar: 'baz' };
};

// Prints: "{ bar: 'baz' }"
console.log(util.inspect(obj));