Skip to content

解压 zip 文件

正常情况下,前端用 unzipper 等库都可以解压。

但是,后端使用:https://github.com/alexmullins/zip,支持 AES 加密,前端很多库都不支持。 最后找到一个库:@zip.js/zip.js

const fs = require('fs')
const path = require('path')

const { BlobReader, BlobWriter, ZipReader } = require('@zip.js/zip.js');

const file = path.join(__dirname, 'a.zip');
const password = '8a0198e592bcdc8716de0dac494e26ee'

async function unzipFile(zipFilePath, outputDir) {
    // Read the zip file
    const zipFileData = fs.readFileSync(zipFilePath);
    const zipFileBlob = new Blob([zipFileData]);

    // Create a ZipReader
    const reader = new ZipReader(new BlobReader(zipFileBlob), { password: password});

    // Get the entries (files and directories) in the zip
    const entries = await reader.getEntries();

    // Ensure the output directory exists
    if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, { recursive: true });
    }

    // Extract each entry
    for (const entry of entries) {
        const entryPath = path.join(outputDir, entry.filename);

        if (entry.directory) {
            // If the entry is a directory, create it
            fs.mkdirSync(entryPath, { recursive: true });
        } else {
            // If the entry is a file, extract it
            const writer = new BlobWriter();
            const blob = await entry.getData(writer);
            const buffer = await blob.arrayBuffer();
            fs.writeFileSync(entryPath, Buffer.from(buffer));
        }
    }

    // Close the ZipReader
    await reader.close();

    console.log('Unzipping completed successfully!');
}


unzipFile(file, './aa')
    .catch(err => console.error('Error unzipping file:', err));