Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Last active August 29, 2015 14:05
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 mlconnor/589db5828994aa957fee to your computer and use it in GitHub Desktop.
Save mlconnor/589db5828994aa957fee to your computer and use it in GitHub Desktop.
A quick first pass at turning request.js options object into a curl command. Much work needed here for escaping and edge cases.
function request2Curl(options) {
var tokens = ['curl', '-v', '-k', '-ssl3'];
if ( _.has(options, 'auth') ) {
if ( _.has(options.auth, 'user') ) {
tokens.push('--user', "'" + options.auth.user + ":" + options.auth.pass + "'");
}
}
var isPost = _.has(options, 'method') && options.method.toLowerCase() == 'post';
if ( isPost ) {
tokens.push('-X', 'POST');
}
if ( _.has(options, 'headers') ) {
_.each(options.headers, function(value,key) {
tokens.push('-H', "'" + key + ':' + value + "'");
});
}
if ( _.has(options, 'json') ) {
tokens.push('-H', "'Content-Type:application/json'");
if ( options.json !== true ) {
tokens.push('-d', "'" + JSON.stringify(options.json) + "'");
}
}
if ( _.has(options, 'qs') ) {
var parsedUrl = url.parse(options.url);
if ( ! isPost ) {
if ( parsedUrl.query == null ) {
parsedUrl.query = options.qs;
} else {
parsedUrl.query = parsedUrl.query + '&' + querystring.encode(options.qs);
}
options.url = url.format(parsedUrl);
}
}
tokens.push("'" + options.url + "'");
return tokens.join(" ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment