【问题标题】:How could I check If a zip file is corrupted in NodeJS?如何检查 NodeJS 中的 zip 文件是否损坏?
【发布时间】:2022-01-15 14:16:54
【问题描述】:

我会使用 NodeJS 使用尽可能少的 CPU 和内存来检查 ZIP 文件是否损坏。

如何损坏 ZIP 文件:

  1. 下载 ZIP 文件
  2. 使用像 Notepad++ 这样优化的文本编辑器打开 ZIP 文件
  3. 重写标题。只放随机字符。

我正在尝试使用 NPM 库“node-stream-zip”来实现这个目标

  private async assertZipFileIntegrity(path: string) {
    try {
      const zip = new StreamZip.async({ file: path });
      const stm = await zip.stream(path);
      stm.pipe(process.stdout);
      stm.on('end', () => zip.close());
    } catch (error) {
      throw new Error();
    }
  }

但是,当我运行单元测试时,我在数组中收到错误:

拒绝值:[错误]

【问题讨论】:

  • 编辑您的问题,向我们展示console.error(error)的输出
  • throw new Error(); 几乎毫无意义。您的 catch 块获取一个包含有用信息的错误对象,您只需将其丢弃并抛出一个空的错误对象,其中没有任何信息。我看不出有任何理由这样做。使用已经提供给您的错误对象,或者如果您要创建自己的错误对象,请从原始错误对象中放入一些有用的信息。

标签: javascript node.js zip


【解决方案1】:

import zip from 'yauzl';
import path from 'path';

const invalidZipPath = path.resolve('invalid.zip');
const validZipPath = path.resolve('valid.zip');

const isValidZipFile = (filePath) => {


    return zip.open(filePath, { lazyEntries: true }, (err, stream ) => {

        if (err) {
            
            console.log('fail to read ', filePath);
            return false;

        }
            
        console.log('success read ', filePath);
        return true;

    });

}

isValidZipFile(validZipPath);
isValidZipFile(invalidZipPath);


【讨论】:

    猜你喜欢
    • 2011-04-26
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多