Node.js - How to open a password-protected .zip file?

Extracting a .zip file is very easy in any language, but when it comes to open a password protected zip in node.js, there are very few libraries and tutorials.

Node.js - How to open a password-protected .zip file?

Extracting a .zip file is very easy in any language, but when it comes to open a password-protected zip in node.js, there are very few libraries and tutorials. Though we can always use OS commands by spawning some child processes, I don't like it that way because sometimes it is not scalable and most of the time it is not OS-agnostic, which might lead to some issues.

So after struggling a bit, I finally solved how to do this with unzipper. Now, let's first install the dependencies and see the code.

To install unzipper, run the following command:

npm i unzipper

(I am using v0.10.5 of unzipper while writing this blog - Just in case if it doesn't work in newer versions)


Code


Explanation

In the code above, first, we're simply importing the library to use it later. And I'm using async/await instead of .then() syntax to prevent the callback hell as you may have some other logic. Also, because of it, the code looks more elegant!

We need to use try/catch because both the await statements may throw an exception.

Open/Load a zip file to extract

Here, we're passing the path to the file in unzipper.Open.file(). This may throw an error if it can't find a specified file.
We can access the files using directory.files which is an array. In our case, the first element, directory.files[0], will have our file.

Extract the loaded zip file

.buffer() returns a promise which resolves buffer content of that file. It throws an error if the file provided is not a zip file, or if it is password-protected and no password or a wrong password is provided.

Reading the content

We can simply convert the extracted buffer to string and read the file content by converting it to the string by extracted.toString().


Footnotes

Do let me know if there is any error or any other better way to do this. Also, If you like the content, you can subscribe to this blog using the form below.