How can we format a value
into a string to be consistent with how console.log(value)
does it?
I need to append extra details to each value I am printing, without breaking the default formatting provided by console.log
. It is easy for simple values, but for such types as Date
and Object
it is more complicated.
Is there a way I can make it consistent with console.log
? In other words, how to format a value
to be the same string as we get from console.log(value)
?
I'm trying to implement a simple library manakin. Here's its complete source code:
'use strict';
(function () {
var error = console.error, warn = console.warn;
console.error = function () {
var a = arguments;
error.apply(this, Object.keys(a).map(function (key) {
return "\u001b[31m" + a[key] + "\u001b[0m";
}));
};
console.warn = function () {
var a = arguments;
warn.apply(this, Object.keys(a).map(function (key) {
return "\u001b[33m" + a[key] + "\u001b[0m";
}));
};
})();
The problem I am having is that for types Date
and Object
the output is different:
// without manakin:
console.warn({value: 1});
//=> { value: 1 }
// with manakin:
console.warn({value: 1});
//=> [object Object]
And I want to make it consistent.
SOLVED
In the end I figured out how to make it all work in both both Node.js and in all browsers, see manakin source code (it is small).
It required different implementation for Node.js and for the browsers. Specifically under Node.js it uses util.inspect
.