How can I get the string that console.log(obj); would print?
I'm using node.js and I'm familiar with
util.inspect(obj)
but it doesn't seem to stringify the same way as console.log(obj);
, not by default, at least. How do I get a string in the same format as console.log(obj);
would print? I'm asking because I'm using a logger (winston.js) and I want it to print objects this way.15 Replies
https://nodejs.org/api/console.html#consolelogdata-args
you can't - it writes directly to the standard output
you can create your own, which writes to a file or something else
or, you can use some linux magic to pass the data around from the standard output into standard input
I think I asked my question in a confusing way and have edited it. Hopefully that is more clear. I'm not trying to get the string from
console.log(obj)
, I'm asking how to create a string with the same value
But your link seems to be saying it can be done with https://nodejs.org/api/util.html#utilformatformat-argsyes, that is what's used to format the data for output
Is
console.log(obj)
roughly equivalent to util.format('%o', obj)
?
or %s
or %O
?it should be
'%O'
ok thanks!
'%s'
should give you the amazing [object Object]
output
but, if you can try it, that's even betterah right. In that case, I want a little better than
console.log(obj)
maybe you want the equivalent to
console.dir()
?I dunno... I think I want
%o
even though it's a little different
that seems like the most useful for troubleshootingyeah I already use that but I don't find it useful unless I set the same settings as
%o
. It's a lot of typing for quick troubleshootingyou can make it into an utility functions
or a class
but that may not be a great idea
What advantage does it have over
util.format('%o', ...
?you can control exactly what it shows
it has a ton of options