Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use curl with exec nodejs

I try to do the following in node js

var command = " -d '{'title': 'Test' }' -H 'Content-Type: application/json' http://125.196.19.210:3030/widgets/test";  

    exec(['curl', command], function(err, out, code) {
        if (err instanceof Error)
        throw err;
        process.stderr.write(err);
        process.stdout.write(out);
        process.exit(code);
    });

It works when I do the below in command line.:
curl -d '{ "title": "Test" }' -H "Content-Type: application/json" http://125.196.19.210:3030/widgets/test

But when I do it in nodejs it tells me that

curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
child process exited with code 2
like image 550
anders Avatar asked Nov 28 '14 13:11

anders


1 Answers

You can do it like so... You can easily swap out execSync with exec as in your above example.

#!/usr/bin/env node

var child_process = require('child_process');

function runCmd(cmd)
{
  var resp = child_process.execSync(cmd);
  var result = resp.toString('UTF8');
  return result;
}

var cmd = "curl -s -d '{'title': 'Test' }' -H 'Content-Type: application/json' http://125.196.19.210:3030/widgets/test";  
var result = runCmd(cmd);

console.log(result);
like image 143
Brad Parks Avatar answered Sep 21 '22 22:09

Brad Parks