0

In javascript, node.js specifically, I sometimes find myself trying to console.log a variable out while debugging. It works well when objects aren't nested too deep.

return Promise.resolve({plain: 'object'})
  .then(console.log);

this prints out

{plan: 'object'}

But with deep nested objects, I have to stringify it to view some of the nested properties.

return Promise.resolve(nestedObj)
  .then(function(obj) {
    console.log(JSON.stringify(obj, null, 2));
  });

Is there a shorter way to simulate the above, that will both call JSON.stringify and console.log?

I'm looking for a 1 liner that in effect executes like

.then -> JSON.stringify -> console.log
Kevin
  • 81
  • 2
  • 9
  • Node.js, so I don't get Chrome's debugging tools. It's sometimes laggy when trying to invoke node's debugger. – Kevin Aug 06 '15 at 07:08
  • I would still need to call `console.log` with the provided output of `util.inspect` or `JSON.stringify` – Kevin Aug 06 '15 at 07:14
  • why not just write a function that does the two lines and then just call the function in each .then() – Code Uniquely Aug 06 '15 at 07:17
  • I guess I'll take "your question has been marked as duplicate" to mean there's no one liner to pretty print or to have nested callbacks without declaring a new anon function – Kevin Aug 06 '15 at 07:25

1 Answers1

-1

You can use console.dir instead of console.log. It displays to one more level deeper. You can also create a global or module local function

function fullLog(obj) 
{
    console.log(JSON.stringify(obj, null, 2));
}

Then use this in your promise.

Peter Paul Kiefer
  • 2,114
  • 1
  • 11
  • 16
  • This would be in effect the same way I'm doing it by creating a anon function and using the param to be called by another. I would like to try to stay away from adding extra global / module local functions just for debugging purposes. – Kevin Aug 06 '15 at 07:20
  • I think it makes a difference if you have a global function or have to write the function on every position you need it. All possible/thinkable solutions (even the console.log function) must be pre implemented. My solution gives you also the posibility to "switch off" the logging if you are in production mode if you comment the `console.log(...` line out. – Peter Paul Kiefer Aug 06 '15 at 08:58