In this tutorial, we’ll explore how to download a file from a Node.js server using the Express framework.
We’ll cover two scenarios: downloading a single file and downloading multiple files as a zipped folder. Express provides a convenient method, res.download()
for handling file downloads.
Downloading a Single File
Let’s create a simple example to download a single file. Assume you have an Express app with a file named app.js
.
// Import necessary modules const express = require('express'); const app = express(); // Set up a route for downloading a single file app.get('/download', function(req, res){ const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`; res.download(file); // Set disposition and send it. }); // Start the server app.listen(3000, function(){ console.log('Server is listening on port 3000'); });
In this example, when a GET request is made to /download
, the server responds by triggering the download of the file dramaticpenguin.MOV
. The res.download()
method automatically sets the appropriate headers for file download.
The browser interprets the response as a file download and prompts the user to choose a location to save the file.
Downloading Multiple Files as a Zipped Folder
To download multiple files as a zipped folder, we’ll use the express-zip
npm package. Install it by running:
npm install express-zip
Now, modify the app.js
file:
// Import necessary modules const express = require('express'); const app = express(); const zip = require('express-zip'); // Set up a route for downloading multiple files as a zip app.get('/download-multiple', function(req, res){ // Define an array of file objects with path and name const files = [ { path: 'path/to/file1.txt', name: 'file1.txt' }, { path: 'path/to/file2.txt', name: 'file2.txt' }, // Add more files as needed ]; // Use res.zip() to send the files as a zip folder res.zip(files); }); // Start the server app.listen(3000, function(){ console.log('Server is listening on port 3000'); });
In this example, when a GET request is made to /download-multiple
, the server responds by sending a zip file containing multiple files specified in the files
array.
The browser prompts the user to download the zip file and choose a location to save it.
Notes
- Remember that the user has control over the download location through their browser settings. They can choose to save files in their default download directory or select a different destination each time.