Home > other >  Unzip single file from zip archive using node.js zlib module
Unzip single file from zip archive using node.js zlib module

Time:10-03

Let say I have a zip archive test.zip which contained two files:

test1.txt and text2.txt

I want to extract only test1.txt using the node inbuilt zlib module.

How to do that?

I don't want to install any package.

CodePudding user response:

Yes, Node.js has a built-in module for doing this so it's not required any extra packages in your project.

const fs = require('fs');
const zlib = require('zlib');

const fileContents = fs.createReadStream('./path_to_zip_file/file1.txt.gz');
const writeStream = fs.createWriteStream('./path_to_unzip_file/file1.txt');
const unzip = zlib.createGunzip();

fileContents.pipe(unzip).pipe(writeStream);

Note: the path may be different in different os(Linux and Windows), so I assume that you run your node application in a Linux machine.

CodePudding user response:

You could run a shell command to unzip, assuming that unzip is installed on your system. (It very likely is.)

As far as I can tell, there is no zip functionality within node.js without installing a package.

You can use zlib to help you with the decompression part, but you will have to write your own code to interpret the zip format. You can use zlib.inflateRaw to decompress the raw deflate compressed data of a zip entry. You have to first find where that compressed data starts by reading and interpreting the zip file headers.

The zip format is documented here.

  • Related