[英]node.js download file with http.request to another api
i'm trying to write file to the file system with data sent as a response of http.request. 我正在尝试使用作为http.request响应发送的数据将文件写入文件系统。 When i call the function file is created on desktop but it contains only text: [Object object]. 当我调用时,功能文件是在桌面上创建的,但仅包含文本:[对象对象]。 Question is how do i get the actual file data from http.request response and how do i write it to a file. 问题是如何从http.request响应中获取实际的文件数据,以及如何将其写入文件。 When i directly call the api from rest client like postman, the file downloads perfectly, but when node sends the call it doensn't work. 当我从诸如邮递员之类的其他客户端直接调用api时,文件会完美下载,但是当节点发送调用时,它将无法正常工作。 Here is my code: 这是我的代码:
exports.fileDownload = function(req, res){
//Options are defined here
var request = http.request(options, function (res, err) {
if(err){
//Error handling
}
});
request.on('error', function (e) {
//Error handling
});
request.on('response', function(data){
fs.writeFile("C:/Users/Test/Desktop/file.txt", data, 'binary', function(err){
if(err){
//Error handling
}
else{
console.log("Done");
}
})
})
request.end()
}
What is wrong here, so when this function is invoked, it creates file named file.txt with [Object object] text in it, and not the actual text of the file. 这是怎么回事,因此,调用此函数时,它将创建名为file.txt的文件,其中包含[Object object]文本,而不是文件的实际文本。 Thanks. 谢谢。
http.request
returns a response object in the callback, containing the headers etc. You have to bind an event handler to that response object and wait for the actual data, something like this : http.request
在回调中返回一个响应对象,其中包含标http.request
。您必须将事件处理程序绑定到该响应对象,然后等待实际数据,如下所示:
exports.fileDownload = function (req, res) {
//Options are defined here
var request = http.request(options, function (resp, err) {
if (err) {
//Error handling
} else {
resp.on('data', function (chunk) {
fs.writeFile("C:/Users/Test/Desktop/file.txt", chunk, function (err) {
if (err) {
//Error handling
} else {
console.log('Done');
}
});
});
}
});
request.end();
}
Perhaps add: 也许加上:
resp.on('end', function () { resp.on('end',function(){
// do something // 做一点事
}); });
You get/send all the data only after the 'end' event fires. 仅在“ end”事件触发后才获取/发送所有数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.