Skip to content
Advertisement

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?

Advertisement

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement