3

res.download is serving up the file but once downloaded it is 0 bytes? Any ideas?

app.get('/download', function(req, res) {
    console.log("download");
    console.log(req.query.fileID);
    fileDownload(req.query.fileID, function(rep){
        if(rep.success){
              console.log("Serving File to User, File: " + rep.data);
              res.download(__dirname +  "/" + rep.data, rep.data)   

        }else{
            console.log(res);
        }
    });
})

A ls on the folder shows the file is there ready for download, the names are correct and all on download box that browser displays but download is always 0 bytes in size.

A check on the file from file file download shoes yes it is there and yes its all good.

ISSUE FOUND MAYBE: I Think the issue is the file is not fully downloaded before its being served to client, see below,i will try adding a callback to the PIPE.....

function fileDownload(id, callback){
    info(id, function(res){
        if(!res.error){
            info(id, function(res){
                if(!res.error){
                    //console.log(res.data);
                    var d = JSON.parse(res.data);
                    //console.log(d['file_name']);
                    var url2 = baseurl + "/api/file/" + id ;
                    var r = request(url2);
                    r.on('response',  function (res) {
                        res.pipe(fs.createWriteStream('./' + d['id'] + d['file_name']));
                        console.log("Download Done: " + './' + d['id'] + d['file_name']);
                        return callback({success:true, data:d['id'] + d['file_name']});
                    });
                }else{
                    console.log("ERROR: " + res.data)
                    return callback({success:false, data: res.data});
                }
            });
        }else{
            console.log("ERROR: " + res.data)
            return callback({success:false, data: res.data});
        }
    });

};
scott
  • 1,531
  • 2
  • 16
  • 29

1 Answers1

1

The issue was due to the file being served up before the stream was finished writing,

fix add .on('close') to the stream.

 r.on('response',  function (res) {
                        res.pipe(fs.createWriteStream('./' + d['id'] + d['file_name']).on('close', function() {
                            console.log('file done');
                            console.log("Download Done: " + './' + d['id'] + d['file_name']);
                            return callback({success:true, data:d['id'] + d['file_name']});
                          }));
                        console.log("You should not see this");

                    });
scott
  • 1,531
  • 2
  • 16
  • 29