How to use curl with exec nodejs

I am trying 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); }); 

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

But when I do this 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 
+9
source share
3 answers

The options parameter of the exec command does not contain your argv.

You can put your parameters directly with child_process.exec function:

  var exec = require('child_process').exec; var args = " -d '{'title': 'Test' }' -H 'Content-Type: application/json' http://125.196.19.210:3030/widgets/test"; exec('curl ' + args, function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); 

If you want to use argv arguments,

You can use the child_process.execFile function:

 var execFile = require('child_process').execFile; var args = ["-d '{'title': 'Test' }'", "-H 'Content-Type: application/json'", "http://125.196.19.210:3030/widgets/test"]; execFile('curl.exe', args, {}, function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); 
+5
source

You can do it like this ... You can easily replace execSync with exec , as in the example above.

 #!/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); 
+3
source

FWIW you can do the same thing initially in node with:

 var http = require('http'), url = require('url'); var opts = url.parse('http://125.196.19.210:3030/widgets/test'), data = { title: 'Test' }; opts.headers = {}; opts.headers['Content-Type'] = 'application/json'; http.request(opts, function(res) { // do whatever you want with the response res.pipe(process.stdout); }).end(JSON.stringify(data)); 
+2
source

Source: https://habr.com/ru/post/978833/


All Articles