2014-11-28 16 views
6

tôi cố gắng làm như sau trong nút jsLàm thế nào để sử dụng curl với exec 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; 
     process.stderr.write(err); 
     process.stdout.write(out); 
     process.exit(code); 
    }); 

Nó hoạt động khi tôi làm dưới đây trong dòng lệnh .:
curl -d '{ "title": "Test" }' -H "Content-Type: application/json" http://125.196.19.210:3030/widgets/test

Nhưng khi tôi làm điều đó trong nodejs nó cho tôi biết rằng

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

Sự cố này có được giải quyết không? – Baart

Trả lời

3

Tham số [tùy chọn] của lệnh exec không có để chứa argv của bạn.

Bạn có thể đặt thông số của bạn trực tiếp với child_process.exec chức năng:

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

Nếu bạn muốn sử dụng các đối số argv,

bạn có thể sử dụng child_process.execFile chức năng:

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

Tôi thích curl - tốt hơn rất nhiều so với bất kỳ ứng dụng HTTP node.js nào – etayluz

2

FWIW bạn có thể làm điều tương tự natively trong nút với:

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

Bạn có thể làm điều đó như vậy ... Bạn có thể dễ dàng trao đổi trên execSync với exec như trong ví dụ trên của bạn.

#!/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); 
Các vấn đề liên quan