Skip to content
Advertisement

Download a file from NodeJS Server using Express

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:

JavaScript

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

Advertisement

Answer

Update

Express has a helper for this to make life easier.

JavaScript

Old Answer

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.

JavaScript

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

JavaScript

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

JavaScript

You can set the header value to whatever you like. In this case, I am using a mime-type library – node-mime, 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.

Advertisement