Skip to content

Instantly share code, notes, and snippets.

@garthk
Created November 27, 2012 04:31
Show Gist options
  • Select an option

  • Save garthk/4152383 to your computer and use it in GitHub Desktop.

Select an option

Save garthk/4152383 to your computer and use it in GitHub Desktop.
log HTTP POSTs
var http = require('http'),
util = require('util'),
MemoryStream = require('memorystream'),
argv = require('optimist')
.usage('Usage: $0 [-a addr] [-p port]')
.options('a', { alias: 'addr', default: '0.0.0.0' })
.options('p', { alias: 'port', default: 1337 })
.options('h', { alias: 'help' })
.check(function(args) { if (args.h !== undefined) { throw ""; }})
.argv;
var addr = argv.a,
port = argv.p;
process.stdout.setMaxListeners(0);
http.createServer(function (req, res) {
if (req.method == 'POST') {
//console.log('POST'); // why does this help?
var ms = new MemoryStream(),
newlined = false,
nlmatch = /\n$/;
ms.pause();
req.on('data', function(chunk) {
newlined = nlmatch.test(chunk);
});
req.pipe(ms, { end : false });
req.on('end', function() {
if (!newlined) {
ms.write('\n');
}
ms.end();
ms.pipe(process.stdout, { end: false });
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Thanks for POSTing.\n');
});
} else {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Usage: POST data to us. Thanks.\n');
}
}).listen(port, addr);
console.log(util.format('Server running at http://%s:%d', addr, port));
@garthk

garthk commented Nov 27, 2012

Copy link
Copy Markdown
Author

Try:

node logposts.js &
curl --data "hello" http://127.0.0.1/

If you uncomment the console.log call in line 19, you'll see:

Server running at http://0.0.0.0:1337
POST
Thanks for POSTing.
hello

If you leave it commented out, the output of the POSTed content is missing:

Server running at http://0.0.0.0:1337
Thanks for POSTing.

Any ideas?

@garthk

garthk commented Nov 27, 2012

Copy link
Copy Markdown
Author

Replacing MemoryStream with morestreams.BufferedStream did the trick, at least for my small POSTs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment