Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adjust console.log behaviour of custom object

Tags:

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?

like image 474
MoeSattler Avatar asked Feb 08 '15 18:02

MoeSattler


2 Answers

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); 
like image 76
JohnnyHK Avatar answered Oct 11 '22 17:10

JohnnyHK


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' 
like image 44
Evan Brierton Avatar answered Oct 11 '22 18:10

Evan Brierton