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 do I find Express.js tutorials on YouTube?
- How do I use Express.js to parse YAML files?
- How do I implement CSRF protection in an Express.js application?
- How do I render a template using Express.js?
- How can I set up X-Frame-Options in ExpressJS?
- How can I use the x-forwarded-for header in Express.js?
- How can I disable the X-Powered-By header in Express.js?
- How can I parse XML data using Express.js?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use Express.js to implement websockets in my application?
See more codes...