expressjsHow do I use adm-zip with Express.js?
Adm-zip is a Node.js module that allows you to create, read and extract zip files. It can be used with Express.js to zip files and folders for download.
To use adm-zip with Express.js, you need to install it as a dependency:
npm install adm-zip
Then, you can require it and use it in your Express.js code:
const express = require('express');
const AdmZip = require('adm-zip');
const app = express();
app.get('/download', (req, res, next) => {
const zip = new AdmZip();
zip.addFile('file1.txt', Buffer.alloc(30), 'Some content for file 1');
zip.addFile('file2.txt', Buffer.alloc(30), 'Some content for file 2');
const zipData = zip.toBuffer();
res.set('Content-Type', 'application/zip');
res.set('Content-Length', zipData.length);
res.set('Content-Disposition', 'attachment; filename=files.zip');
res.send(zipData);
});
app.listen(3000);
This code creates a new AdmZip
object, adds two files to it and converts it to a buffer. Then, it sets the response headers and sends the zip file.
Code explanation
- Install adm-zip:
npm install adm-zip
- Require adm-zip:
const AdmZip = require('adm-zip');
- Create a new
AdmZip
object:const zip = new AdmZip();
- Add files to the zip object:
zip.addFile('file1.txt', Buffer.alloc(30), 'Some content for file 1');
- Convert the zip object to a buffer:
const zipData = zip.toBuffer();
- Set response headers:
res.set('Content-Type', 'application/zip');
- Send the buffer:
res.send(zipData);
Helpful links
More of Expressjs
- How do I manage user roles in Express.js?
- How do I disable CORS in Express.js?
- How can I use express-zip js to zip and download files?
- How do I download a zip file using Express.js?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use Zipkin to trace requests in Express.js?
- How do I use Express.js to handle asynchronous requests?
- What is Express.js and how is it used for software development?
- How do I use Zod with Express.js?
- How can I use Express.js to develop a web application?
See more codes...