z3efga
Last Updated: March 07, 2016
·
5.982K
· dpashkevich
D42a7264714dee5006b9c99d2567a320

Pretty print JSON from command line with NodeJS

Inspired by this protip: Commandline JSON Pretty Print everywhere.

I was pretty sure it can be done in less code in NodeJS since JSON format is native to the language but the "one-liner" I came up with so far looks pretty ugly:

echo '{"hello": 1, "foo": "bar"}' | xargs -0 node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 2))"

The esoteric goal was to not use any external modules :)

Since NodeJS deals with stdin asynchronously and the stream is paused by default, I figured it's shorter to just use some help from the good ol' xargs to convert stdin to arguments.

Anybody has a better solution? :)

Say Thanks
Respond

2 Responses
Add your response

3158
Ebd63577f6cef101bf22245572781d5d

It would be nice to do something like this:

echo '{"hello": 1, "foo": "bar"}' | node -e "process.stdin.pipe(console.dir)"

Maybe with streams2

over 1 year ago ·
9393
B04f09671622481fff88959fd0430d1e

Save this on your PATH. Read the first arg as the file or read stdin. When piping to it, /dev/stdin will look like a file and get and EOF when it's done... assuming your JSON doesn't overrun the memory, it should work.

#!/usr/bin/env node
var args = process.argv.splice( /node$/.test(process.argv[0]) ? 2 : 1 );
console.log(
    JSON.stringify(
        JSON.parse(
            require('fs') .readFileSync(
                args.length > 0 ? args[0] : "/dev/stdin"
            )
        ), null, 4)
);
over 1 year ago ·