Как преобразовать файл в zip-архив и загрузить его с помощью NodeJS?
Zip-файлы - это распространенный способ хранения сжатых файлов и папок. В этой статье я продемонстрирую, как преобразовать файл в zip-формат с помощью модуля adm-zip (NPM PACKAGE).
Использование ADM-ZIP
- сжать исходный файл и преобразовать его в формат zip.
- обновить / удалить существующие файлы (формат .zip).
Установка ADM-ZIP:
Шаг 1: Установите модуль, используя следующую команду в терминале.
npm установить adm-zip
Шаг 2: Проверьте версию установленного модуля с помощью приведенной ниже команды.
npm vresion adm-zip
Мы собираемся заменить эту папку upload_data на zip-файл с помощью модуля adm-zip!

upload_data ПАПКА
Code for conversion and downloading zip file:
Javascript
// express is a node framework that is helps in creating// 2 or more web-pages applicationconst express = require("express") // filesystem is a node module that allows us to work with// the files that are stored on our pcconst file_system = require("fs") // it is an npm package.this is to be required in our JS // file for the conversion of data to a zip file!const admz = require("adm-zip") // stores the express module into the app variable!const app = express() // this is the name of specific folder which is to be // changed into zip file1var to_zip = file_system.readdirSync(__dirname+"/"+"upload_data") // this is used to request the specific file and then print // the data in it!app.get("/",function(req,res){ res.sendFile(__dirname+"/"+"index.html") // zp is created as an object of class admz() which // contains functionalities var zp = new admz(); // this is the main part of our work! // here for loop check counts and passes each and every // file of our folder "upload_data" // and convert each of them to a zip! for(var k=0 ; k<to_zip.length ; k++){ zp.addLocalFile(__dirname+"/"+"upload_data"+"/"+to_zip[k]) } // here we assigned the name to our downloaded file! const file_after_download = "downloaded_file.zip"; // toBuffer() is used to read the data and save it // for downloading process! const data = zp.toBuffer(); // this is the code for downloading! // here we have to specify 3 things: // 1. type of content that we are downloading // 2. name of file to be downloaded // 3. length or size of the downloaded file! res.set("Content-Type","application/octet-stream"); res.set("Content-Disposition",`attachment; filename=${file_after_download}`); res.set("Content-Length",data.length); res.send(data); }) // this is used to listen a specific port!app.listen(7777,function(){ console.log("port is active at 7777");}) |
Шаги по запуску программы:
- Наш проект выглядит так:

последний проект
Откройте терминал на желаемом локальном компьютере и убедитесь, что вы загрузили пакет adm-zip, используя следующую команду.
npm установить adm-zip
Запустите файл app.js, используя следующую команду.
узел app.js

приложение работает
Откройте браузер и откройте localhost: 7777, а затем папка upload_data преобразуется в zip-файл и загружается!

изменен на zip файл
Результат: Представление всей процедуры преобразования файла в zip-файл с помощью следующего gif, таким образом, вы можете изменить свою папку на zip-файл, а затем загрузить его!

файл в zip файл