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
res.download(filePath, fileName);
});
The above file can be used to download a file located in the nodejs server location. res.download 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.
- Best practices for unsubscribing from subscriptions of Observables in Angular
- 10 best practices for creating Angular Application
- How to GroupBy in MongoDB
- How to Join two collections in MongoDB
- How to take screenshot on Android Phone- Samsung, Redmi Note
Happy Coding 🙂