Node.js : Specify files to unzip with zlib + tar

前端 未结 2 1112
粉色の甜心
粉色の甜心 2020-12-30 09:40

An installation process is downloading a .tar.gz archive, then extract the files to a destination directory. However, not all the files in the archive are requi

相关标签:
2条回答
  • 2020-12-30 10:20

    It works similar to the unzip module:

    var fs = require('fs');
    var tar = require('tar');
    var zlib = require('zlib');
    var path = require('path');
    var mkdirp = require('mkdirp'); // used to create directory tree
    
    var log = console.log;
    
    var tarball = 'path/to/downloaded/archive.tar.gz';
    var dest    = 'path/to/destination';
    
    fs.createReadStream(tarball)
      .on('error', log)
      .pipe(zlib.Unzip())
      .pipe(tar.Parse())
      .on('entry', function(entry) {
        if (/\.js$/.test(entry.path)) { // only extract JS files, for instance
          var isDir     = 'Directory' === entry.type;
          var fullpath  = path.join(dest, entry.path);
          var directory = isDir ? fullpath : path.dirname(fullpath);
    
          mkdirp(directory, function(err) {
            if (err) throw err;
            if (! isDir) { // should really make this an `if (isFile)` check...
              entry.pipe(fs.createWriteStream(fullpath));
            }
          });
        }
      });
    
    0 讨论(0)
  • 2020-12-30 10:38

    You can take a look at this post to find a good solution.

    By the way, in the zlib-documentation you'll see that you can specify a "buffer" calling .unzip().

    0 讨论(0)
提交回复
热议问题