Skip to content

Instantly share code, notes, and snippets.

@cdahlqvist
Created May 21, 2015 09:11
Show Gist options
  • Save cdahlqvist/3712a73acf2b712ef06d to your computer and use it in GitHub Desktop.
Save cdahlqvist/3712a73acf2b712ef06d to your computer and use it in GitHub Desktop.
var http = require('http');
var fs = require('fs');
var optimist = require('optimist')
.usage('Simple web server to log incoming requests.\n\nUsage: $0 [options]')
.options({
file: {
alias: 'f',
describe: 'Path of file to log to. Server will log to stdout if no file specified.'
},
port: {
alias: 'p',
describe: 'Port to listen to. Defaults to 8000.',
type: 'number',
default: 8000
},
help: {
describe: 'Display help message',
type: 'boolean'
}
});
var argv = optimist.argv;
if (argv.help) {
optimist.showHelp(console.log);
process.exit();
}
if (argv.file) {
try {
argv.output_file = fs.openSync(argv.file, "a+");
}
catch (e) {
console.log('Error opening output file %s: %s', argv.file, e.message);
process.exit;
}
}
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
var timestamp = new Date().toISOString();
if (argv.output_file) {
var logline = timestamp + ': ' + req.method + ' ' + req.url + ' ' + body + '\n';
fs.writeSync(argv.output_file, logline);
} else {
console.log('%s: %s %s %s', timestamp, req.method, req.url, body);
}
res.writeHead(200);
res.end();
});
}).listen(argv.port, '0.0.0.0');
console.log('Server running at http://0.0.0.0:%d/', argv.port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment