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
ἔρως
ἔρως2w ago
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
DanKaplanSES
DanKaplanSESOP2w ago
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-args
ἔρως
ἔρως2w ago
yes, that is what's used to format the data for output
DanKaplanSES
DanKaplanSESOP2w ago
Is console.log(obj) roughly equivalent to util.format('%o', obj)? or %s or %O?
ἔρως
ἔρως2w ago
it should be '%O'
DanKaplanSES
DanKaplanSESOP2w ago
ok thanks!
ἔρως
ἔρως2w ago
'%s' should give you the amazing [object Object] output but, if you can try it, that's even better
DanKaplanSES
DanKaplanSESOP2w ago
ah right. In that case, I want a little better than console.log(obj)
ἔρως
ἔρως2w ago
maybe you want the equivalent to console.dir()?
DanKaplanSES
DanKaplanSESOP2w ago
I dunno... I think I want %o even though it's a little different that seems like the most useful for troubleshooting
DanKaplanSES
DanKaplanSESOP2w ago
yeah 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 troubleshooting
ἔρως
ἔρως2w ago
you can make it into an utility functions or a class but that may not be a great idea
DanKaplanSES
DanKaplanSESOP2w ago
What advantage does it have over util.format('%o', ...?
ἔρως
ἔρως2w ago
you can control exactly what it shows it has a ton of options

Did you find this page helpful?