如何使用curl和exec nodejs

13

我试图在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);
    });

在命令行中执行以下命令可以正常工作:
curl -d '{ "title": "Test" }' -H "Content-Type: application/json" http://125.196.19.210:3030/widgets/test

但是当我在Node.js中执行时,它告诉我:

curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
child process exited with code 2

这个问题解决了吗? - Baart
3个回答

10
你可以这样做... 你可以像上面的例子一样轻松地将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);

1
有人可以告诉我,为什么这个被踩了吗?谢谢! - Tino

10

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);
    }
});

2
我喜欢curl - 比任何node.js的HTTP客户端都好。 - etayluz

1

如果你愿意,你可以在Node中以本地方式完成同样的事情:

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));

对于https,您应该使用https模块。 - mscdex
当然,但如果您事先不知道URL模式,则可能是HTTP或HTTPS。 另外OP问如何使用curl,而不是如何下载文件(最好使用fetchaxios)。 - Yves M.
你可以解析URL并检查结果对象中的协议,以了解要使用哪个内置模块。 - mscdex
原始问题是如何使用curl而不是HTTP库来完成它。 - ajimix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接