📜  如何将文件转换为 zip 文件并使用 Node.js 下载?

📅  最后修改于: 2022-05-13 01:56:42.332000             🧑  作者: Mango

如何将文件转换为 zip 文件并使用 Node.js 下载?

Zip 文件是存储压缩文件和文件夹的常用方法。在本文中,我将演示如何使用 adm-zip 模块 (NPM PACKAGE) 将文件转换为 zip 格式。

ADM-ZIP 的使用

  • 压缩原始文件并将其更改为 zip 格式。
  • 更新/删除现有文件(.zip 格式)。

ADM-ZIP的安装:

第 1 步:在终端中使用以下命令安装模块。

npm install adm-zip

第 2 步:使用以下命令检查已安装模块的版本。

npm version adm-zip

我们将使用 adm-zip 模块将此 upload_data 文件夹更改为 zip 文件!

上传数据文件夹

转换和下载 zip 文件的代码:

Javascript
// express is a node framework that is helps in creating
// 2 or more web-pages application
const express = require('express')
  
// filesystem is a node module that allows us to work with
// the files that are stored on our pc
const 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 file1
var 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


运行程序的步骤:

  1. 我们的项目看起来像:

最终项目

在所需的本地打开终端并确保您已使用以下命令下载了 adm-zip 包。

npm install adm-zip

使用以下命令运行 app.js 文件。

node app.js

应用程序正在运行

打开浏览器并打开localhost:7777然后将upload_data文件夹转换为 zip 文件并下载!

更改为 zip 文件

输出:借助下面的 gif 表示将文件转换为 zip 文件的整个过程,因此您可以通过这种方式将文件夹更改为 zip 文件然后下载!

文件到压缩文件