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'