Home>Article>Web Front-end> A brief analysis of zip compression and zip decompression in Node (with code)

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

奋力向前
奋力向前 forward
2021-09-03 11:14:33 4486browse

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)-LinuxonzipRelated commands

Use adm-zip

adm-zipsupports one or more ofarchiveandunarchiveThe 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

zipobject one by one, and the content needs to be added manually, and then the file writing operation is used to convert thezipobject 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 afoldermethod, but it is only used Switch the virtual path inside thezipobject, for examplezip.folder("img").file('a.txt')is to add one inzipimgsubdirectory, createa.txtbelow, the effect is equivalent tozip.file("img/a.txt"). It should also be noted here that the contents of the file need to be added manually. If it is justzip.file("a.txt"); the content is just created in thezipobject. An emptytxtfile, 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 , supportszipformattarformat, 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 82b87f1621993e4ff2b6f091d2e68692][-x 28897b20adb25fbae118a3f80f538dec] or unzip [-Z]

Additional instructions:

unzip Decompressor for .zipcompressed 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.

-pis similar to the-cparameter. It will display the decompression result on the screen, but will not perform any conversion.

-tCheck whether the compressed file is correct.

-uis similar to the-fparameter, 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.

-MSend the output results to themoreprogram for processing.

-nDo not overwrite the original file when decompressing.

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

-P3b0c6630ad8a929436e205e60a78d070 Use the password option ofzip.

-qNo information is displayed during execution.

-sConvert whitespace characters in file names to underscore characters.

-VKeep the file version information ofVMS.

-XWhen decompressing, the originalUID/GIDof the file will be saved at the same time.

[.zip file]Specify the.zipcompressed file.

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

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

-xa88d6c965e22043f423e8b4df11da793Specifies which files in the.zipcompressed file are not to be processed.

-Z unzip-Zis equivalent to executing thezipinfocommand.

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:chuchur.com. If there is any infringement, please contact admin@php.cn delete