2014-06-11 61 views
0

寫入文件,我發送下一個POST請求:的Node.js /從響應

var post_data = JSON.stringify({ 
    'uuid': '00d25', 
    'file': 'ORIGINAL', 
    'store' : 'someStore' 
}); 
console.log("B"); 
// An object of options to indicate where to post to 
var post_options = { 
    'host': 'localhost', 
    'port': '5000', 
    'path': '/getDocu', 
    'method': 'POST', 
    'headers': { 
     'Content-Type': 'application/json' 
    } 
}; 

// Set up the request 
var post_req = http.request(post_options, function(res) { 
     // Here I need to get the data response 
} 

我想創建一個文件,並把所有我從響應獲取數據。所以我試試這個:

res.setEncoding('utf8'); 
     var writeStream = fs.createWriteStream("C://Client//something4.txt"); 

     res.on('data', function (chunk) { 
      writeStream.write(chunk); 
     }); 
     res.on('end', function() { 
      writeStream.close(); 
     }) 

但是我看到我只得到這個文件的一部分(65KB/258KB),而不是整個文件。

我做什麼了?

回答

1

在您有機會將所有內容寫入磁盤之前,您可能正在關閉文件句柄。

因爲資源是一個流,你應該嘗試以下操作:

res.setEncoding('utf8'); 
var writeStream = fs.createWriteStream("C://Client//something4.txt"); 
res.pipe(writeStream);