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

我与影子孤独终老i 提交于 2019-12-18 13:14:30

问题


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 required, and I'd like to specify which files should be extracted. The naïve way would be to delete the unnecessary files after extraction, but I'd like a "cleaner" way and filter out instead.

Is this possible?

The (relevant) code I have so far is (stripped for readability)

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

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.Extract({ path: dest }))
  .on("end", log);

Thank you.


回答1:


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



回答2:


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().



来源:https://stackoverflow.com/questions/21989460/node-js-specify-files-to-unzip-with-zlib-tar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!