Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active December 14, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/5153772 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/5153772 to your computer and use it in GitHub Desktop.
Reads JSON from standard input and writes equivalent nicely-formatted JSON to standard output.

formatjson

This Literate CoffeeScript program reads JSON from standard input and writes equivalent nicely-formatted JSON to standard output.

Define a couple of short variable names for the Node.js stdin and stdout members.

stdin = process.stdin
stdout = process.stdout

Set the standard-input encoding to utf8 so that we receive data as a string, and invoke resume() so that we receive input data.

stdin.setEncoding 'utf8'
stdin.resume()

As data is read from standard input, save it to an array of "chunks".

inputChunks = []
stdin.on 'data', (chunk) -> inputChunks.push chunk

When we reach the end of the data, join all the chunks into a single string, parse it as JSON, reformat it, and write it to standard output. Terminate the output with a newline and we're done.

stdin.on 'end', () ->
    inputJSON = inputChunks.join()
    parsedData = JSON.parse inputJSON
    outputJSON = JSON.stringify parsedData, null, '    '

    stdout.write outputJSON
    stdout.write "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment