如何将 curl 与 exec nodejs 一起使用

How to use curl with exec nodejs

本文关键字:nodejs 一起 exec curl      更新时间:2023-09-26

>我尝试在节点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);
    }
});
你可以

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