adjust console.log behaviour of custom object

is there any way to influence what console.log gives out custom objects? I tried to overwrite the customObject.prototype.toString method, that did not work though.

Any ideas?

Answers:

Answer

In node.js, console.log calls util.inspect on each argument without a formatting placeholder. So if you define an inspect(depth, opts) method on your object it will be called to get your custom string representation of the object.

For example:

function Custom(foo) {
    this.foo = foo;
}

Custom.prototype.inspect = function(depth, opts) {
    return 'foo = ' + this.foo.toUpperCase();
};

var custom = new Custom('bar');
console.log(custom);

Outputs:

foo = BAR

Or using a class:

class Custom {
    constructor(foo) {
        this.foo = foo;
    }

    inspect(depth, opts) {
        return 'foo = ' + this.foo.toUpperCase();
    }
}

var custom = new Custom('bar');
console.log(custom);
Answer

The previous answer has been deprecated in newer versions of node. The method one needs to implement now is the symbol [util.inspect.custom].

For example:

const util = require('util');

class Custom {
  constructor(foo, bar) {
    this.foo = foo;
    this.bar = bar;
  }

  [util.inspect.custom](depth, opts) {
    return this.foo + this.bar;
  }
}

console.log(new Custom(3, 5)); // Prints '8'

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.