Richard Richard - 1 year ago 73
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


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?


Answer Source

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' }"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download