Javascript 如何将curl与exec nodejs一起使用
我尝试在NodeJS中执行以下操作Javascript 如何将curl与exec nodejs一起使用,javascript,node.js,curl,Javascript,Node.js,Curl,我尝试在NodeJS中执行以下操作 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;
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);
});
当我在命令行中执行以下操作时,它会工作。:/br>
curl-d'{“title”:“Test”}'-H“内容类型: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\u进程直接输入参数。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\u 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));
你可以这样做。。。您可以轻松地将
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);
这个问题解决了吗?我喜欢curl——比node.js HTTP clients好多了。有人能告诉我,为什么这被否决了吗?谢谢对于https,您将使用
https
模块。当然可以,但如果您事先不知道URL模式。。。它可以是HTTP或HTTPS。。OP还询问了如何使用curl,而不是如何下载文件(最好使用fetch
或axios
),您可以解析url并从结果对象中检查协议,以了解要使用的内置模块。