Chaitu Chaitu - 1 month ago 7
Javascript Question

How to download a file from project/specific location using nodejs?

This may be a dumb question but I am lil confused, my requirement is I should be able to download an excel template on a click event, I thought I will put that excel template in some folder(docs) in my backend code(instead of generating it dynamically) and download that. Is that possible, if yes how? I am using express and node.

Answer

It is possible. Probably you use Express framework. Express can serve static files under '/public' folder. When user connect to this file, her/his browser will download file. But some browser can view files online. For example, Chrome can open PDF files. If you want to force to download file you can use this simple code;

app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
  res.download(file); // Set disposition and send it.
});