Is it possible (feasible) to format (fold) Node.js terminal output JSON?
I'm a frontend developer, and I'm unfamiliar with command line tools for Node.js
I currently use iTerm with zShell, but I can't find any resources online about folding console output (similar to how the Chrome console formats objects). I tried using fx but can't seem to pipe and utilize the Node output through the util.
node -e 'console.log({ a: { b: 2 } })';
node -e 'console.log(JSON.stringify({ a: { b: 2 } }, null, 2))';
For large network objects, it would be much more convenient to fold the nested layers. It would also be great to have syntax highlighting.
Is there an easy way to debug Node.js console output JSON?
Am I missing fundamental CLI tools? I know this is a relatively open-ended question, but I think it would be a good resource for other people in my situation (I've spent ~3 hours researching with barely any improvement).
Thanks
The problem with the first line is that node
command doesn't produce valid JSON string when you use console.log
. You need to encode the object as JSON string yourself.
The second line correctly encodes the object as JSON string (using stringify
):
node -e 'console.log(JSON.stringify({ a: { b: 2 } }, null, 2))'
To pipe the JSON string output of the node
command you need to omit the semicolon ;
. The semicolon in bash is used to separate commands. More information about what semicolon means in bash: docstore.mik.ua/orelly/unix3/upt/ch28_16.htm
This is how you can pipe the ouptut to fx
:
node -e 'console.log(JSON.stringify({ a: { b: 2 } }, null, 2))' | fx
And this is how you would pipe th output to jq
:
node -e 'console.log(JSON.stringify({ a: { b: 2 } }, null, 2))' | jq
fx
will be probably more intuitive to use.jq
might come in handy if you need to deal with large outputs.
jq is a lightweight and flexible command-line JSON processor.
Here is some information on how to install it: stedolan.github.io/jq/download
And here is a tutorial on how to do some basic filtering with jq
:
stedolan.github.io/jq/tutorial
It's worth mentioning that Node.js can be debugged by listening to localhost:9229
In my case:
- I went to
chrome://inspect/#devices
- Opened Node.js debugger
- changed
localhost:9229
to127.0.0.1:9229
on 'Connections' panel ... this took a few hours to discover - made and ran a package.json command
"debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --config=jest.config.js --timeout=60000 --runInBand",
- accepted debugging in the Node.js sources panel and console.log didn't work, but watching variables was convenient
View Logs with Google Chrome
- Run your Node server with the
--inspect
flag
$ node --inspect server.js
- Open a new tab in Google Chrome and go to
chrome://inspect/#devices
- Now click on
inspect
to view all logs with the browser console