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?
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);
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With