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"
See http://undefinedvalue.com/2013/03/01/os-x-automator-service-reformatting-json-text