How to untar file in node.js

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

There are some untar libraries, but I cannot get them working.

My idea would be something like

untar(bufferStreamOrFilePath).extractToDirectory("/path", function(err){}) 

Is something like this available?

回答1:

Just an update on this answer, instead of node-tar, consider using tar-fs which yields a significant performance boost, as well as a neater interface.

var tarFile = 'my-other-tarball.tar'; var target = './my-other-directory';  // extracting a directory fs.createReadStream(tarFile).pipe(tar.extract(target)); 


回答2:

The tar-stream module is a pretty good one:

var tar = require('tar-stream')      var extract = tar.extract(); extract.on('entry', function(header, stream, callback) {     // make directories or files depending on the header here...     // call callback() when you're done with this entry });  fs.createReadStream("something.tar").pipe(extract)  extract.on('finish', function() {     console.log('done!') }); 


回答3:

A function to extract a base64 encoded tar fully in memory, with the assumption that all the files in the tar are utf-8 encoded text files.

const tar=require('tar'); let Duplex = require('stream').Duplex;  function bufferToStream(buffer) {     let stream = new Duplex();     stream.push(buffer);     stream.push(null);     return stream; }   module.exports=function(base64EncodedTar){     return new Promise(function(resolve, reject){         const buffer = new Buffer.from(base64EncodedTar, "base64");          let files={};          try{              bufferToStream(buffer).pipe(new tar.Parse())                 .on('entry', entry => {                     let file={                         path:entry.path,                         content:""                     };                     files[entry.path]=file;                     entry.on('data', function (tarFileData) {                         file.content += tarFileData.toString('utf-8');                     });                      // resolve(entry);                 }).on('close', function(){                   resolve(files);                 });         } catch(e){             reject(e);         }      })  };


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