adjust console.log behaviour of custom object

Recent (18) Node.js version has this documentation snippet as an example of how to do this across Node and Browsers:

const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');

class Password {
  constructor(value) {
    this.value = value;
  }

  toString() {
    return 'xxxxxxxx';
  }

  [customInspectSymbol](depth, inspectOptions, inspect) {
    return `Password <${this.toString()}>`;
  }
}

const password = new Password('r0sebud');
console.log(password);
// Prints Password <xxxxxxxx>

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'

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);