【问题标题】:How to use curl with exec nodejs如何使用 curl 与 exec nodejs
【发布时间】:2015-01-27 04:23:58
【问题描述】:

我尝试在节点 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

【问题讨论】:

  • 这个问题解决了吗?

标签: javascript node.js curl


【解决方案1】:

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

【讨论】:

  • 我喜欢 curl - 比任何 node.js HTTP 客户端都好
【解决方案2】:

您可以这样做...您可以轻松地将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);

【讨论】:

  • 有人可以告诉我,为什么这被否决了?谢谢!
【解决方案3】:

FWIW 你可以在 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 模块。
  • 当然,但如果你事先不知道 URL 架构......它可能是 HTTP 或 HTTPS.. OP 还询问如何使用 curl,而不是如何下载文件(最好使用 @987654323 @ 或axios)
  • 您可以解析 url 并从结果对象中检查协议以了解要使用哪个内置模块。
猜你喜欢
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2022-01-23
  • 2023-03-16
  • 2018-06-15
  • 2019-09-18
  • 2019-01-05
相关资源
最近更新 更多