Learn how to decompress .zip files easily in Electron Framework.

How to extract content of .zip files (decompress) in Electron Framework

Before you can start actually using the content (files) in a zip file, you must unzip it. In this article, you'll learn how to unpack .zip files with Electron Framework and the decompress-zip module.

Requirements

In order to decompress files in Electron, you'll need the decompress-zip module, this module allow you to extract files from a ZIP archive with a couple lines of code. To install decompress-zip file in your project, execute the following command in your command prompt:

npm install decompress-zip

After the installation you'll be able to require the module in your code using require('decompress-zip'). Visit the repository of the module in Github for more information.

Implementation

With decompress-zip you'll be able to execute 2 tasks: unpack a .zip file and list the content of a .zip file.

Decompress (unpack .zip file)

To decompress a.zip file, we are going to use the unzipper.extract method. This method extracts the contents of the ZIP archive file and returns an EventEmitter with two possible events: error triggered in case of error, and extract when the extraction has completed.

The value passed to the extract event is a basic log of each file and how it was compressed. To unzip a file you need to provide only the current path of the zip file and the destination directory:

var ZIP_FILE_PATH = "C:/path/to/file/myzipfile.zip";
var DESTINATION_PATH = "C:/desktop/examplefolder";
var unzipper = new DecompressZip(ZIP_FILE_PATH);

// Add the error event listener
unzipper.on('error', function (err) {
    console.log('Caught an error', err);
});

// Notify when everything is extracted
unzipper.on('extract', function (log) {
    console.log('Finished extracting', log);
});

// Notify "progress" of the decompressed files
unzipper.on('progress', function (fileIndex, fileCount) {
    console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
});

// Start extraction of the content
unzipper.extract({
    path: DESTINATION_PATH
    // You can filter the files that you want to unpack using the filter option
    //filter: function (file) {
        //console.log(file);
        //return file.type !== "SymbolicLink";
    //}
});

If you want to filter files while you decompress, as shown before, you can rely on the filter property in the unzipper.extract method (if the returned value is true, then the file will be unpacked). A file object (in the filter callback) contains all the following properties:

{  
   "_offset":40,
   "_maxSize":34348,
   "parent":".",
   "filename":"image4.png",
   "path":"image4.png",
   "type":"File",
   "mode":438,
   "compressionMethod":8,
   "modified":"2016-10-18T14:25:12.000Z",
   "crc32":1376504589,
   "compressedSize":34348,
   "uncompressedSize":34381,
   "comment":"",
   "flags":{  
      "encrypted":false,
      "compressionFlag1":false,
      "compressionFlag2":false,
      "useDataDescriptor":false,
      "enhancedDeflating":false,
      "compressedPatched":false,
      "strongEncryption":false,
      "utf8":false,
      "encryptedCD":false
   }
}

The following example shows a basic implementation of decompress-zip using the native dialogs of electron.

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>Electron Zip Uncompress Files</title>
	 
</head>

<body>

    <input type="button" id="select-file" value="Select .zip file" />
    
	<script>
        var DecompressZip = require('decompress-zip');
        var app = require('electron').remote;
        var dialog = app.dialog;

        (function () {
            function uncompress(ZIP_FILE_PATH, DESTINATION_PATH){
                var unzipper = new DecompressZip(ZIP_FILE_PATH);

                // Add the error event listener
                unzipper.on('error', function (err) {
                    console.log('Caught an error', err);
                });
                
                // Notify when everything is extracted
                unzipper.on('extract', function (log) {
                    console.log('Finished extracting', log);
                });
                
                // Notify "progress" of the decompressed files
                unzipper.on('progress', function (fileIndex, fileCount) {
                    console.log('Extracted file ' + (fileIndex + 1) + ' of ' + fileCount);
                });
                
                // Unzip !
                unzipper.extract({
                    path: DESTINATION_PATH
                });
            }

            document.getElementById("select-file").addEventListener("click", () => {
                // Select the .zip file
                dialog.showOpenDialog({
                    title:"Select the .zip file to decompress"
                },function (fileNames) {
                    // fileNames is an array that contains the selected file
                    if(fileNames === undefined){
                        console.log("No file selected");
                        return;
                    }else{
                        // Select destination folder
                        dialog.showOpenDialog({
                            title:"Select destination folder where the content should be decompressed",
                            properties: ["openDirectory"]
                        },function (folderPaths) {
                                // folderPaths is an array that contains all the selected paths
                            if(fileNames === undefined){
                                console.log("No destination folder selected");
                                return;
                            }else{
                                // Proceed to decompress
                                uncompress(fileNames[0], folderPaths[0]);
                            }
                        });
                    }
                });          
            }, false);
        })();
    </script>
</body>

</html>

The previous code will create a simple application with a button that allow you to select a .zip file to be unpacked:

Select .zip file browser

You can (if you want) filter only the .zip files in the filebrowser by adding the filters property at the initialization of the filebrowser:

dialog.showOpenDialog({
    title:"Select the .zip file to decompress",
    filters: [
        {name: '.ZIP Files', extensions: ['zip']},
        {name: 'All Files', extensions: ['*']}
    ]
}, (fileNames) => {
    // The rest of the code here
});

Select only .zip file browser

Then it will store the path of the file in a variable, and will start once again a dialog that allow you to choose a folder where the content of the zip file should be decompressed:

Select browser to decompress .zip file

According to the previous actions, the Downloads.zip file will be decompressed in the Desktop/example folder. Once you select the folder, the decompression will start showing the progress in the console and saving the files in the destination folder:

Decompressed .zip file with electron

List .zip file content

You can list the content of a file without decompress it directly using the unzipper.list method. The list method is much like extract, except that the success event list the data for the event. Besides, the retrieven array provide the paths of the files, that means that no files are actually extracted. The list method doesn't expects arguments.

The following snippet should l

var ZIP_FILEPATH = "C:/path/to/file/myzipfile.zip";

// Require DecompressZip module
var DecompressZip = require('decompress-zip');

// Declare the unzipper class
var unzipper = new DecompressZip(ZIP_FILEPATH);
 
// Add the error event listener
unzipper.on('error', (err)  => {
    console.log('Caught an error', err);
});

// Add the list event listener that will be triggered when the unzipper can list the content
unzipper.on('list', (files) => {
    // Show the array of items in the console
    console.log(files);
});

// Trigger to list the content of the zip file
unzipper.list();

The following HTML document in electron show how to list the content of a .zip file (drag and drop a .zip file to list the content in the console).

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>Electron Zip List Files</title>
	<style>
		#drag-file {
			background-color: blue;
            color:white;
			text-align: center;
            width:300px;
            height:300px;
		}
	</style>
</head>

<body>
	<div id="drag-zip">
		<p>Drag your zip files here to list content on the console</p>
	</div>
    
	<script>
        var DecompressZip = require('decompress-zip');

        (function () {
            var holder = document.getElementById('drag-zip');
            
            holder.ondragover = holder.ondragleave = holder.ondragend = () => {
                return false;
            };

            holder.ondrop = (e) => {
                e.preventDefault();

                var firstFile = e.dataTransfer.files[0];

                if(!firstFile){
                    console.log("No file given");
                    return;
                }

                var unzipper = new DecompressZip(firstFile.path);
 
                unzipper.on('error', (err)  => {
                    console.log('Caught an error', err);
                });
                
                unzipper.on('list', (files) => {
                    console.log('The zip file contains:');
                    console.log(files);
                });
                
                unzipper.list();
                                 
                return false;
            };
        })();
    </script>
</body>

</html>

The implementation of the previous example in Electron should give as result:

Electron list .zip file

As you can see, to extract .zip files is pretty easy with this module created by Bower. Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors