Thiago Miranda de Oliveira Thiago Miranda de Oliveira - 1 year ago 201
Node.js Question

Download a file from NodeJS Server using Express

Probably a dumb question but how can I download a file that is in my server to my machine accessing a page in a nodeJS server?

I'm using the ExpressJS and I've been trying this:

app.get('/download', function(req, res){

var file = fs.readFileSync(__dirname + '/upload-folder/dramaticpenguin.MOV', 'binary');

res.setHeader('Content-Length', file.length);
res.write(file, 'binary');

But I can't get the file name and the file type ( or extension ). Can anyone help me with that?

Thank you very much

Answer Source

As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.

res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');

You may also want to send a mime-type such as this:

res.setHeader('Content-type', 'video/quicktime');

If you want something more in-depth, here ya go.

var path = require('path');
var mime = require('mime');

app.get('/download', function(req, res){

  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);

You can set the header value to whatever you like. In this case, I am using a mime-type library,, to check what the mime-type of the file is.

Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.


Express has a helper for this to make life easier.

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