expressjsHow do I download a zip file using Express.js?
To download a zip file using Express.js, you need to use the res.download()
function.
The code below shows an example of how to use res.download()
to download a zip file.
// Import the Express module
const express = require('express');
// Create an Express application
const app = express();
// Create a route
app.get('/download', (req, res) => {
// Set the file path
const filePath = './myZipFile.zip';
// Set the file name
const fileName = 'myZipFile.zip';
// Use res.download() to download the file
res.download(filePath, fileName);
});
// Start the server
app.listen(3000, () => console.log('Server listening on port 3000!'));
The output of the code above will be:
Server listening on port 3000!
When a request is made to http://localhost:3000/download
, the file myZipFile.zip
will be downloaded.
Code explanation
require('express')
: This imports the Express module.const app = express()
: This creates an Express application.app.get('/download', (req, res) => { ... })
: This creates a route which will handle the download request.const filePath = './myZipFile.zip'
: This sets the file path of the zip file.const fileName = 'myZipFile.zip'
: This sets the file name of the zip file.res.download(filePath, fileName)
: This uses the Expressres.download()
function to download the zip file.app.listen(3000, () => console.log('Server listening on port 3000!'))
: This starts the server on port 3000.
More of Expressjs
- How can I use Express.js to create a validator?
- How do I manage user roles in Express.js?
- How can I use express-zip js to zip and download files?
- How do I set the time zone in Express.js?
- How do I find Express.js tutorials on YouTube?
- How do I use Zod with Express.js?
- How do I use Express.js to handle asynchronous requests?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I use Express.js to parse YAML files?
- How can I use Express.js to yield results?
See more codes...