Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract single file from tar.gz archive using node js

var targz = require('tar.gz');
var extract = new targz().extract(targzFile , destnDir, function(err){
if(err)
     console.log(err);
console.log('The extraction has ended :'+counter);
});

The above code extracts targzFile to destnDir, however I would want to extract single file from targzFile.

Thanks in advance.

like image 282
user2992082 Avatar asked Nov 14 '13 13:11

user2992082


2 Answers

For anyone interested in the answer, it is possible using streams and the module tar-stream. Here is a complete example that extracts a file called documents.json from the archive archive.tar.gz:

var tar = require('tar-stream');
var fs = require('fs');
var zlib = require('zlib');

var extract = tar.extract();
var data = '';

extract.on('entry', function(header, stream, cb) {
    stream.on('data', function(chunk) {
    if (header.name == 'documents.json')
        data += chunk;
    });

    stream.on('end', function() {
        cb();
    });

    stream.resume();
});

extract.on('finish', function() {
    fs.writeFile('documents.json', data);
});

fs.createReadStream('archive.tar.gz')
    .pipe(zlib.createGunzip())
    .pipe(extract);
like image 142
Gianni Valdambrini Avatar answered Nov 15 '22 00:11

Gianni Valdambrini


This simple snippet is working for me, and unzips zipped.tgz into downloaded.json :

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

const os = fs.createWriteStream('downloaded.json');
fs.createReadStream('zipped.tgz')
        .pipe(zlib.createGunzip())
        .pipe(os);
like image 35
OhadR Avatar answered Nov 14 '22 23:11

OhadR