2019-08-11 A console.dir hint

As everyone knows, console.log is the ultimate debugging tool. ;-) Joking aside, it is genuinely useful (together with console.error) in scripts. I often write small (and sometimes not so small) CLI utilities in Node.js, and they are really indispensable.

Sometimes, however, you want to output a complicated structure. You can use JSON.stringify, but it’s not always what you want, since some structures may be circular, and JSON.stringify will barf at them. Then, of course, console.dir is your friend.

What if console.dir is not enough? Maybe you need to go deeper than the default two levels. Maybe you want the result to go to stderr instead of stdout. Maybe you want to have the keys sorted. If you find any of those (potentially) useful, check out util.inspect. It turns out that console.dir(...) is equivalent to console.log(util.inspect(...)), so you can console.error(util.inspect(...)) to print to stderr. Also, util.inspect accepts an optional argument, allowing for all things I hinted at above and more. Good to know!

CategoryEnglish, CategoryBlog, CategoryJavaScript