Abhishek Anand
Abhishek Anand

Reputation: 477

Downloading zip file through node.js fails the first time, but works in subsequent tries

I have a router to download certain files. However, the zip file doesn't get downloaded the first time around, its stuck on starting. However on the second try, everything works perfectly fine. Is there something wrong I am doing? The createfile function just creates a file which are being zipped

app.post('/downlaod_file',ensureAuthenticated,(req,res)=>{
    var json_array=[];
        for (var i = 0, len = req.body.idlist.length; i < len; i++) {
            var path = createfile(req.body.idlist[i])
            json_array.push({
                path: 'file_' + req.body.idlist[i] + '.docx' ,
                name: 'file' + req.body.idlist[i] + '.docx'
            })

        }
        res.zip(json_array);
});

Upvotes: 0

Views: 125

Answers (1)

Jim B.
Jim B.

Reputation: 4714

I believe your problem is simply that the file is created the first time, but not ready in time to return it. The second time you make the call the file is there already so it works.

I would recommend modifying your createFile to either take a callback or return a promise when the operation is complete. Then use the completion of createFile to delay the call to res.zip(). That will ensure the file is complete before returning a response.

Upvotes: 1

Related Questions