Skip to content

Instantly share code, notes, and snippets.

@edgar
Last active December 11, 2015 13:59
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 edgar/4611560 to your computer and use it in GitHub Desktop.
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/
#!/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