user2992082
user2992082

Reputation: 91

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.

Upvotes: 9

Views: 20101

Answers (3)

OhadR
OhadR

Reputation: 8839

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);

Upvotes: -3

Greg Brown
Greg Brown

Reputation: 53

This is old, but Gianni's solution didn't quite work for me, maybe because he was extracting text files, I'm not sure.

Also, you can optimize quite a bit by only checking the header name once instead of for every data chunk for every file record.

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

var extract = tar.extract();
var chunks = [];

extract.on('entry', function(header, stream, next) {
    if (header.name == 'documents.bin') {
        stream.on('data', function(chunk) {
            chunks.push(chunk);
        });
    }

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

    stream.resume();
});

extract.on('finish', function() {
    if (chunks.length) {
        var data = Buffer.concat(chunks);
        fs.writeFile('documents.bin', data);
    }
});

fs.createReadStream('archive.tar.gz')
    .pipe(zlib.createGunzip())
    .pipe(extract);

Upvotes: 3

Gianni Valdambrini
Gianni Valdambrini

Reputation: 316

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);

Upvotes: 14

Related Questions