Home > Back-end >  How can I stringify any type of value the same way console.log does?
How can I stringify any type of value the same way console.log does?

Time:12-12

Like the title says, how can I stringify a value of any type and get the exact same output console.log would print, or a very similar and still useful print, in a variable, instead of going to the console. Preferably in Deno.

.toString() works nice on Error() and other similar functions, but returns [object Object] on your more traditional objects. Likewise, JSON.stringify() works nice on your more traditional objects, but returns {} on stuff like Error(). Since these are both objects, I'm basically wondering, what would be the best way to get the most optimal output with objects, when you don't know beforehand what type it will be.

CodePudding user response:

Console behaviour isn't defined by the ECMAScript specification, so a given runtime can implement that however its maintainers see fit. E.g. quoting MDN:

The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided.

Deno does expose the inspect function:

inspect(value: unknown, options?: InspectOptions): string

Converts the input into a string that has the same format as printed by console.log().

Node has util.inspect which is similar, although not explicitly tied to the console behaviour:

The util.inspect() method returns a string representation of object that is intended for debugging.

  • Related