我发送下一个 POST 请求:
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),而不是整个文件。
我做错了什么?
最佳答案
您可能在有机会将所有内容写入磁盘之前就关闭了文件句柄。
由于 res 是一个 Stream,您应该尝试以下操作:
res.setEncoding('utf8');
var writeStream = fs.createWriteStream("C://Client//something4.txt");
res.pipe(writeStream);
关于javascript - node.js/从响应写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24163159/