Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active December 31, 2015 15:09
Show Gist options
  • Save amatiasq/8005079 to your computer and use it in GitHub Desktop.
Save amatiasq/8005079 to your computer and use it in GitHub Desktop.
A node script than opens a server and creates a bash script per each request, containing the curl command to replicate the request it received.
#!/usr/bin/env node
//jshint node:true
'use strict';
var fs = require('fs');
var url = require('url');
var http = require('http');
var port = process.argv[2];
var folder = process.argv[3];
var counts = {};
folder = folder ? folder + '/' : '';
if (!port) {
console.error('Usage: ', process.argv[1], 'port:Number folder:Optional');
process.exit(1);
}
if (folder && !fs.existsSync(folder))
fs.mkdirSync(folder);
function getFilename(path) {
counts[path] = counts[path] || 0;
var number = counts[path]++;
var parsed = url.parse(path);
var cleaned = parsed.pathname
.replace(/\//g, '_')
.replace(/^_|_$/g, '');
var filename = cleaned + '.' + number + '.sh'
return folder + filename;
}
function end(response) {
response.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
});
response.end();
}
function escape(text) {
return '\'' + text.replace(/'/g, '\'"\'"\'') + '\'';
}
http.createServer(function(request, response) {
if (request.method === 'OPTIONS')
return end(response);
var data = '';
request.on('data', function(chunk) { data += chunk });
request.on('end', function() {
var script = [ '#/bin/bash\n\ncurl', '-X', request.method ];
// headers
Object.keys(request.headers).forEach(function(header) {
script.push('\\\n\t-H', escape(header + ': ' + request.headers[header]));
});
// request body
script.push('\\\n\t-d', escape(data));
// url
script.push('\\\n\t' + escape('http://localhost:' + port + request.url));
// save
var filename = getFilename(request.url);
console.log('Saving', filename);
fs.writeFile(filename, script.join(' '));
end(response);
});
}).listen(port);
console.log('Listening at port', port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment