2014-12-19 50 views
2

我正在努力研究如何獲取衍生子進程的輸出並將該輸出提供給多部分mime上傳。將spawn過程的管道輸出轉換爲superagent upload

這裏是我有一個據我可以告訴應該工作

var request = require('superagent'); 
var spawn = require('child_process').spawn; 

var spawned = spawn('echo', ['hello', 'world']); 

request.post('http://localhost/api/upload') 
    .attach('file', spawned.stdout) 
    .end(function(res) { 
     console.log("DONE", res); 
    }); 

不幸的是,這將引發從節點而無益Error: socket hang up響應。

回答

0

你很貼心!

下面是最終版本,你想要做什麼:

var sys = require('sys') 
var exec = require('child_process').exec; 

var request = require('superagent'); 

exec('echo hello world', function(err, stdout, stderr) { 
    request.post('http://localhost/api/upload') 
    .attach('file', stdout) 
    .end(function(res) { 
     console.log('DONE', res); 
}); 

我使用exec在這裏,因爲它的回調函數輸出的輸出和錯誤流,它似乎像你想要的。

+0

感謝您的建議。 我重寫了你的例子,因爲Superagent真的不喜歡用緩衝區而不是Streams。我用下面的代碼替換了它:https://gist.github.com/hash-bang/f897f72fa8048ebb315d 這個的確如你所說的那樣工作。可惜我找不到用Streams做這項工作的方法。 – 2014-12-21 06:40:56

+0

啊,沒有意識到:對不起,< – rdegges 2014-12-21 20:50:16

+0

你的方法工作正常,只是使用緩衝區而不是Streams。經過多次實驗,我仍然無法找到一種方法來完成這項工作。 – 2014-12-21 20:52:43