How to Download a file in NodeJS- ExpressJS?


Downloading a file is a common requirement when working with applications. At times you want some user data formatted in the desired format to be downloaded and provided to the user. We will provide code to download files in node js using express.

Code to download file in express JS NodeJS

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use, fileName);    

The above file can be used to download a file located in the nodejs server location. is the method in the response object which returns the file to be downloaded to the requestor.

filepath: is the location of the file on the node server.

filename: It is the name that the browser will use for the downloaded file.

So as per your requirement of providing formatted data to users or providing help files to users, you can use the code mentioned above to download files from nodejs server using express js.

In case looking for some other options, you can try some solutions mentioned in the article here.

Happy Coding 🙂

How to Download a file in NodeJS- ExpressJS?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top