在Node.js中解压缩密码保护文件



是否有一个库,我可以用它来解压缩密码保护的文件(网站让我在下载文件时设置密码)?有很多库可以解压缩普通文件,但我找不到一个可以用密码解压缩的库。

在这里我找到了一些有用的初学者。但我宁愿不使用child_process和使用内置的unix解压缩功能,但这可能是我最后的手段。我甚至可以在加密代码上执行我自己的操作,但我甚至无法找出如何确定加密类型(它似乎只是非常标准的,因为我可以在终端中执行)。

我宁愿不这样做,但恐怕这是我唯一的选择,所以我尝试了以下方法:

var fs = require('fs')
, unzip = require('unzip')
, spawn = require('child_process').spawn
, expand = function(filepath, cb) {
     var self = this
     , unzipStream = fs.createReadStream(filepath).pipe(unzip.Parse())
     , xmlData = '';
     unzipStream.on('entry', function (entry) {
            var filename = entry.path;
           // first zip contains files and one password protected zipfile. 
           // Here I can just do pipe(unzip.Parse()) again, but then i just get a giant encoded string that I don't know how to handle, so i tried other things bellow.
           if(filename.match(/.zip$/)){
                 entry.on('data', function (data) {
                     var funzip = spawn('funzip','-P','ThisIsATestPsswd','-');
                     var newFile = funzip.stdin.write(data);
            // more closing code...

然后我有点不知所措。我试着写newFile到一个文件,但那只是说[object]

然后我试着做一些更简单的事情,把最后3行改成

   fs.writeFile('./tmp/this.zip', data, 'binary');
   var newFile = spawn('unzip','-P','ThisIsATest','./tmp/this.zip');
   console.log('Data: ' + data);

但是数据没有任何用处,只是[object Object]。我不知道下一步该怎么做才能把这个新的解压缩文件变成一个工作文件,或者一个可读的字符串。

我是Node的超级新手,所有的异步/侦听器被其他进程触发仍然有点混乱,所以我很抱歉,如果任何这都没有意义。非常感谢你的帮助!

编辑:


我现在添加了以下代码:

var fs = require('fs')
  , unzip = require('unzip')
  , spawn = require('child_process').spawn
  , expand = function(filepath, cb) {
    var self = this
    , unzipStream = fs.createReadStream(filepath)
      .pipe(unzip.Parse())
    , xmlData = '';
      unzipStream.on('entry', function (entry) {
        var filename = entry.path
            , type = entry.type // 'Directory' or 'File'
            , size = entry.size;
        console.log('Filename: ' + filename);
        if(filename.match(/.zip$/)){
            entry.on('data', function (data) {
              fs.writeFile('./lib/mocks/tmp/this.zip', data, 'binary');
              var newFile = spawn('unzip','-P','ThisIsATestPassword', '-','../tmp/this.zip');
              newFile.stdout.on('data', function(data){
                 fs.writeFile('./lib/mocks/tmp/that.txt', data); //This needs to be something different
                    //The zip file contains an archive of files, so one file name shouldn't work
              });
           });
          } else { //Not a zip so handle differently }
       )};
    };

这似乎真的很接近我需要的,但是当文件被写入时,它只有unzip的选项列表:

UnZip 5.52 of 28 February 2005, by Info-ZIP.  Maintained by C. Spieler.  Send
bug reports using http://www.info-zip.org/zip-bug.html; see README for details.
Usage: unzip [-Z] [-opts[modifiers]] file[.zip] [list] [-x xlist] [-d exdir]
  Default action is to extract files in list, except those in xlist, to exdir;
  file[.zip] may be a wildcard.  -Z => ZipInfo mode ("unzip -Z" for usage).
  -p  extract files to pipe, no messages     -l  list files (short format)
  -f  freshen existing files, create none    -t  test compressed archive data
  -u  update files, create if necessary      -z  display archive comment
  -x  exclude files that follow (in xlist)   -d  extract files into exdir
modifiers:                                   -q  quiet mode (-qq => quieter)
  -n  never overwrite existing files         -a  auto-convert any text files
  -o  overwrite files WITHOUT prompting      -aa treat ALL files as text
  -j  junk paths (do not make directories)   -v  be verbose/print version info
  -C  match filenames case-insensitively     -L  make (some) names lowercase
  -X  restore UID/GID info                   -V  retain VMS version numbers
  -K  keep setuid/setgid/tacky permissions   -M  pipe through "more" pager
Examples (see unzip.txt for more info):
  unzip data1 -x joe   => extract all files except joe from zipfile data1.zip
  unzip -p foo | more  => send contents of foo.zip via pipe into program more
  unzip -fo foo ReadMe => quietly replace existing ReadMe if archive file newer

我不确定输入是否错误,因为这看起来像unzip的错误。或者我只是写错了内容。我本以为它会像通常从控制台中执行的那样执行—只是在将所有文件解压缩到目录时添加它们。虽然我希望能够从缓冲区中读取所有内容,但-选项似乎无法做到这一点,因此我将满足于将文件添加到目录中。非常感谢任何有任何建议的人!

编辑2


我能够让这个工作,不是最好的方式,但它至少使用这行:

var newFile = spawn('unzip', [ '-P','ThisIsATestPassword', '-d','./lib/tmp/foo','./lib/mocks/tmp/this.zip' ])

这将把所有文件解压缩到目录中,然后我就可以从那里读取它们了。我的错误是第二个参数必须是一个数组

我能够让这个工作,不是最好的方式,但它至少使用这一行:

var newFile = spawn('unzip', [ '-P','ThisIsATestPassword', '-d','./lib/tmp/foo','./lib/mocks/tmp/this.zip' ])

这将把所有文件解压缩到目录中,然后我就可以从那里读取它们了。我的错误是第二个参数必须是一个数组。

我找到了使用解拉链的解决方案。

从这个博客粘贴代码

const unzipper = require('unzipper');
(async () => {
  try {
    const directory = await unzipper.Open.file('path/to/your.zip');
    const extracted = await directory.files[0].buffer('PASSWORD');
    console.log(extracted.toString()); // This will print the file content
  } catch(e) {
    console.log(e);
  }
})();

正如@codyschaaf在他的回答中提到的,我们可以使用spawn或其他child_process,但它们并不总是与操作系统无关。因此,如果我在生产中使用它,如果存在的话,我总是会选择一个与操作系统无关的解决方案。

我尝试了spawn方法(spawnSync实际上效果更好)。

const result = spawnSync('unzip', ['-P', 'password', '-d', './files', './files/file.zip'], { encoding: 'utf-8' })

然而,这种方法并没有完全工作,因为它引入了一个新的错误:

Archive:  test.zip
   skipping: file.png                need PK compat. v5.1 (can do v4.6)

最终,我选择了7zip方法:

import sevenBin from '7zip-bin'
import seven from 'node-7z'
const zipPath = './files/file.zip'
const downloadDirectory = './files'
const zipStream = seven.extractFull(zipPath, downloadDirectory, {
  password: 'password',
  $bin: sevenBin.path7za
})
zipStream.on('end', () => {
  // Do stuff with unzipped content
})

要解压缩密码保护的压缩多级文件夹,请尝试以下代码。我正在使用unzipper npm.

unzipper.Open.file(contentPath + filename).then((mainDirectory) => {
return new Promise((resolve, reject) => {
  let maindirPath = mainDirectory.files[0].path;
  let patharray = maindirPath.split("/")
  let temppath = destinationPath+patharray[0];
   fs.mkdirSync(temppath);//create parent Directory 
 
    // Iterate through every file inside there (this includes directories and files in subdirectories)
    for (let i = 0; i < mainDirectory.files.length; i++) {
        const file = mainDirectory.files[i];
        let filepath = Distinationpath + file.path
        
        if(file.path.endsWith("/")) {
            fs.mkdirSync(filepath);
        }
        else {
     
            file.stream(password).pipe(fs.createWriteStream(filepath))
                .on('finished', resolve)
                .on('error', reject);
        }
    }
});
});

最新更新