Last active
December 11, 2015 13:59
-
-
Save edgar/4611560 to your computer and use it in GitHub Desktop.
nicerest -- pipe your REST API `curl` calls through this for nicer output. Based on http://code.activestate.com/recipes/577549-nicerest-pretty-print-json-output/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// | |
// nicerest -- pipe your REST API `curl` calls through this for nicer output | |
// | |
// $ curl -is http://search.twitter.com/search.json?q=node.js | nicerest | |
// | |
var stdin = process.openStdin(); | |
var EventEmitter = require('events').EventEmitter; | |
var buffer = ""; | |
stdin.setEncoding('utf8'); | |
stdin.on('data', function (chunk) { | |
buffer += chunk; | |
}); | |
stdin.on('end', function () { | |
if (buffer.slice(0,5) === "HTTP/") { | |
var index = buffer.indexOf('\r\n\r\n'); | |
var sepLen = 4; | |
if (index == -1) { | |
index = buffer.indexOf('\n\n'); | |
sepLen = 2; | |
} | |
if (index != -1) { | |
process.stdout.write(buffer.slice(0, index+sepLen)); | |
buffer = buffer.slice(index+sepLen); | |
} | |
} | |
if (buffer[0] === '{' || buffer[0] === '[') { | |
try { | |
process.stdout.write(JSON.stringify(JSON.parse(buffer), null, 2)); | |
process.stdout.write('\n'); | |
} catch(ex) { | |
process.stdout.write(buffer); | |
if (buffer[buffer.length-1] !== "\n") { | |
process.stdout.write('\n'); | |
} | |
} | |
} else { | |
process.stdout.write(buffer); | |
if (buffer[buffer.length-1] !== "\n") { | |
process.stdout.write('\n'); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment