繁体   English   中英

如何在exec nodejs中使用curl

[英]How to use curl with exec nodejs

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

您可以这样做...您可以轻松地将execSyncexec交换,如上例所示。

#!/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你可以在节点中本地做同样的事情:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM