[英]How to use curl with exec nodejs
I try to do the following in node js 我尝试在节点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 但是当我在nodejs中这样做时,它会告诉我
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
child process exited with code 2
The options
parameter of the exec command is not there to contains your argv. exec命令的
options
参数不包含你的argv。
You could put your parameters directly with the child_process.exec
function : 您可以直接使用
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);
}
});
If you want to use the argv arguments, 如果要使用argv参数,
you can use child_process.execFile
function: 你可以使用
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);
}
});
You can do it like so... You can easily swap out execSync
with exec
as in your above example. 您可以这样做...您可以轻松地将
execSync
与exec
交换,如上例所示。
#!/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);
FWIW you can do the same thing natively in node with: 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.