如何与exec nodejs一起使用curl
我尝试在节点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); });
它在我在命令行执行下面的工作
curl -d '{ "title": "Test" }' -H "Content-Type: application/json" http://125.196.19.210:3030/widgets/test
但是,当我在nodejs中做它,告诉我这一点
curl: no URL specified! curl: try 'curl --help' or 'curl --manual' for more information child process exited with code 2
exec命令的[options]参数不包含argv。
你可以直接用你的参数child_process.exec函数:
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); } });
如果你想使用argv参数,
你可以使用child_process.execFile函数:
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); } });
FWIW您可以在节点中本地执行相同的操作:
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));
你可以像这样做…你可以轻松地用exec
来replaceexecSync
,就像你上面的例子一样。
#!/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);