Skip to content

Instantly share code, notes, and snippets.

@muhqu
Created November 3, 2014 08:11
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 muhqu/573adbbab56f7d146487 to your computer and use it in GitHub Desktop.
Save muhqu/573adbbab56f7d146487 to your computer and use it in GitHub Desktop.
Node.js HTTP Server that writes incoming requests as JSON stream to STDOUT

Usage

$ PORT=1234 http2json &
[1] 52577
$ curl -X GET :1234/HelloWorld
{"Time":1414602104,"Method":"GET","URL":"/HelloWorld","Body":null}
ok
$ curl -X PUT :1234/Foo -d Bar
{"Time":1414602240,"Method":"PUT","URL":"/Foo","Body":"Bar"}
ok
$ kill %+
[1]+  Exit 143                PORT=1234 ./http2json
#!/usr/bin/env node
require('http')
.createServer(function (req, res) {
var body = null;
req.on('data', function (data) {
if (body === null) body = "";
body += data;
});
req.on('end', function () {
process.stdout.write(JSON.stringify({
"Time" : Math.ceil(new Date().getTime()/1000),
"Method" : req.method,
"URL" : req.url,
"Body" : body
}) + "\n");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("ok");
});
}).listen(process.env.PORT || 8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment