DEV Community

Pankaj Kumar
Pankaj Kumar

Posted on

How To Zip And Download Files In Nodejs

In this article, We will see how to create zip in nodejs express application. Since many times we need to download zip file in our web application.

Its very easy to do with nodejs express. Have a look on the below code snippet.

const express = require('express')
const app = express()
const port = 3000;
const AdmZip = require('adm-zip');

app.get('/', (req, res) => {

const zip = new AdmZip();

zip.addLocalFile("./file1.txt");
zip.addLocalFile("./file2.js");
zip.addLocalFile("./file3.ts");

const downloadName = `${Date.now()}.zip`;
const data = zip.toBuffer();
res.set('Content-Type','application/octet-stream');
res.set('Content-Disposition',`attachment; filename=${downloadName}`);
res.set('Content-Length',data.length);
res.send(data);

})

app.listen(port, () => console.log(`Server is running over port ${port}!`))
Enter fullscreen mode Exit fullscreen mode

Click here to find more about the adm-zip package.

So in this article, We learn how to create zip and download it with nodejs.

That’s all for now. Thank you for reading and I hope this artible will be very helpful to understand how to create zip and download it with nodejs.

This article was originally posted over jsonworld

Top comments (0)