Node.js – Extract a file from archive using unzip module

This tutorial shows how to display the extract a file from a given archive (zip/jar/rar etc) using unzip module and node.js.
This uses the following node modules

  • unzip

  • File System


1) Install unzip module

Unzip module provides simple APIs for parsing and extracting zip files. Refer to unzip documentation for more detail.
To install this module, run the following command at the command prompt in your working directory

c:\kalliphant> npm install unzip

2) ExtractFileFromArchive.js Java Script

Following javascript reads the zip file specified (at line 5 in below script) and extract the given file from archive file.
Create the below script in your working directory where you installed above npm modules.

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

var inputFileName = 'C:/kalliphant/';
var fileToExtract = "directory/file_to_extract";
var extractToDirectory = 'C:/kalliphant/outputdir';

	.on('entry', function (entry) {

		if (entry.path === fileToExtract) {
			console.log('Extracting file ' + fileToExtract);

			var fileName = fileToExtract.replace(/^.*[/]/, '');
			entry.pipe(fs.createWriteStream(extractToDirectory + fileName));
		} else {

3) Run the script

If you run the script, it will read the zip file specified and display list of contents.
Below is the sample output and it should extract directory/file_to_extract to output directory specified

c:\kalliphant>node ExtractFileFromArchive.js
Extracting file C:/kalliphant/outputdir/file_to_extract