search
HomeWeb Front-endJS TutorialA brief analysis of zip compression and zip decompression in Node (with code)

In the previous article "What you need to know about certbot to enable Amazon EC2 host https (code sharing)", we learned about certbot to enable Amazon EC2 host https. The following article will introduce you to zip compression and zip decompression in Node. Let's see how to do it.

A brief analysis of zip compression and zip decompression in Node (with code)

##NodeJSFile (folder) compression/decompression scheme(zip/unzip)-Linuxon zipRelated commands

Use adm-zip

adm-zip supports one or more of archive and unarchive The function of a file or an entire folder is very simple and convenient to use.

var adm_zip = require("adm-zip");

//creating archives
var zip = new adm_zip();
zip.addLocalFolder("./dist");
zip.writeZip("./dist.zip");

//extracting archives
var unzip = new adm_zip("dist.zip");
unzip.extractAllTo("./dist", /*overwrite*/ true);

More apihttps://github.com/cthackers/adm-zip

Use JSZip

This library needs to be used when using Files are added to the

zip object one by one, and the content needs to be added manually, and then the file writing operation is used to convert the zip object in the memory into physical storage. So if it is for an entire folder, it is very troublesome. You need to traverse the folder

var JSZip = require("jszip");
var fs = require("fs");

var zip = new JSZip();

var file_content = fs.readFileSync("archive/a.txt");

zip.file("a.txt", file_content);

var data = fs.readFileSync("archive/img/pic.jpeg");
zip.file("img/pic.jpeg", data, { base64: true });

var zipfolder = zip.generate({ type: "nodebuffer" });

fs.writeFile("jszip.zip", zipfolder, function (err) {
  if (err) throw err;
});

JSZipThere is also a folder method, but it is only used Switch the virtual path inside the zip object, for example zip.folder("img").file('a.txt') is to add one in zip img subdirectory, create a.txt below, the effect is equivalent to zip.file("img/a.txt"). It should also be noted here that the contents of the file need to be added manually. If it is just zip.file("a.txt"); the content is just created in the zip object. An empty txt file, and it only exists in the memory and needs to be written to the file before it is actually saved to the disk.

More APIhttps://github.com/Stuk/jszip

Use archiver and unzip

archiverVery powerful , supports zip formattar format, you only need to provide the path to compress an existing folder.

Compression:

// require modules
var fs = require("fs");
var archiver = require("archiver");

// create a file to stream archive data to.
var output = fs.createWriteStream(__dirname + "/example.zip");
var archive = archiver("zip", {
  zlib: { level: 9 }, // Sets the compression level.
});

// pipe archive data to the file
archive.pipe(output);

// append a file from stream
var file1 = __dirname + "/file1.txt";
archive.append(fs.createReadStream(file1), { name: "file1.txt" });

// append a file from string
archive.append("string cheese!", { name: "file2.txt" });

// append a file from buffer
var buffer3 = Buffer.from("buff it!");
archive.append(buffer3, { name: "file3.txt" });

// append a file
archive.file("file1.txt", { name: "file4.txt" });

// append files from a sub-directory and naming it `new-subdir` within the archive
archive.directory("subdir/", "new-subdir");

// append files from a sub-directory, putting its contents at the root of archive
archive.directory("subdir/", false);

// append files from a glob pattern
archive.glob("subdir/*.txt");

// finalize the archive (ie we are done appending files but streams have to finish yet)
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
archive.finalize();

Decompression

var fs = require("fs");
var unzip = require("unzip");

fs.createReadStream("archiver-unzip.zip").pipe(
  unzip.Extract({ path: "unarchive" })
);

More APIhttps://github.com/archiverjs/node-archiver

zip/unzip command on Linux

apt-get install zip unzip

Unzip

zipFile

Syntax: unzip [-cflptuvz][-agcjlmnoqsvx][-P ][-x ] or unzip [-Z]

Additional instructions:

unzip Decompressor for .zip compressed files.

Parameters:

-cDisplay the decompression result on the screen and convert the characters appropriately.

-fUpdate existing files.

-lDisplay the files contained in the compressed file.

-p is similar to the -c parameter. It will display the decompression result on the screen, but will not perform any conversion.

-tCheck whether the compressed file is correct.

-u is similar to the -f parameter, but in addition to updating existing files, other files in the compressed file will also be decompressed into the directory.

-vDisplay detailed information when executing.

-zOnly display the comment text of the compressed file.

-aConvert the necessary characters to the text file.

-bDo not perform character conversion on text files.

-CFile names in compressed files are case-sensitive.

-jDo not process the original directory path in the compressed file.

-LChange all file names in the compressed file to lowercase.

-M Send the output results to the more program for processing.

-nDo not overwrite the original file when decompressing.

-oNo need to ask the user first, unzipoverwrites the original file after execution.

-P<password> Use the password option of </password>zip.

-qNo information is displayed during execution.

-sConvert whitespace characters in file names to underscore characters.

-VKeep the file version information of VMS.

-X When decompressing, the original UID/GID of the file will be saved at the same time.

[.zip file]Specify the .zip compressed file.

[File]Specify which files in the .zip compressed file are to be processed.

-dSpecify the directory where the file will be stored after decompression.

-xSpecifies which files in the .zip compressed file are not to be processed.

-Z unzip-Z is equivalent to executing the zipinfo command.

The basic usage is: zip [parameter][packaged file name] [packaged directory path]

Parameter:

-aConvert the file to ASCII mode

-FTry to repair the damaged compressed file

-hDisplay the help interface

-mAfter compressing the file, delete the source file

-n特定字符串 不压缩具有特定字尾字符串的文件

-o将压缩文件内的所有文件的最新变动时间设为压缩时候的时间

-q安静模式,在压缩的时候不显示指令的执行过程

-r将指定的目录下的所有子目录以及文件一起处理

-S包含系统文件和隐含文件(S 是大写)

范 例:

zip命令可以用来将文件压缩成为常用的zip格式。unzip命令则用来解压缩zip文件。 压缩文件abc.txt和一个目录dir1,名字test.zip

zip -r test.zip abc.txt dir1
#解压缩:
```sh
unzip test.zip

目录下有abc1.zipabc2.zipabc3.zip,使用通配符

unzip abc\?.zip

注释:?表示一个字符,如果用*表示任意多个字符。 不解压,只查看内容

unzip -v test.zip

验证zip文件完成性,查看网上下的包包是不是已经下载完了

unzip -t test.zip

我用-v选项发现music.zip压缩文件里面有很多目录和子目录,并且子目录中其实都是歌曲mp3文件,我想把这些文件都下载到第一级目录,而不是一层一层建目录:

unzip -j music.zip

推荐学习:JS视频教程

The above is the detailed content of A brief analysis of zip compression and zip decompression in Node (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:禅境花园. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.