kkyrazis
kkyrazis

Reputation: 31

Express res.download() not actually downloading file

I'm attempting to return generated files to the front end through Express' res.download function. I'm using chrome, but whenever I call that API that executes the following code all that is returned is the same values returned from the Express res.sendFile() function.

I know that res.download uses res.sendFile, but I would like the download function to actually save to the file system instead of just returning the file in the body of the response.

This is my code.

exports.download = function(req,res) {
    var filePath = //somefile that I want to download
    res.download(filePath, 'response.txt', function(err) {
        throw err;
    }
}

I know that the above code at least partly works because I'm getting back, in the response, the contents of the file. However, I want it to be saved onto the file system.

Am I misunderstanding what the download function is supposed to do? Do I just need to take the response data and write it to the file system manually?

Upvotes: 3

Views: 5707

Answers (1)

Aaron Dufour
Aaron Dufour

Reputation: 17505

res.download adds headers that suggest to the browser that the file should be downloaded rather than opened. However, there's no way to force the browser to do this; it's ultimately the user's choice whether to download a particular file, typically.

If you're triggering this request with AJAX, well, that's not going to cause it to be downloaded, because your JavaScript is requesting that it get the data.

Do I just need to take the response data and write it to the file system manually?

You don't have file system access in browser-side JavaScript. I'm not sure how you intend to do this.

Upvotes: 2

Related Questions