简体   繁体   中英

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. 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. 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. 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. 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 :

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 () {

// do something

});

You get/send all the data only after the 'end' event fires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM