UNPKG

@lark-project/cli

Version:

飞书项目插件开发工具

73 lines (72 loc) 2.91 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var _a; Object.defineProperty(exports, "__esModule", { value: true }); const jszip_1 = __importDefault(require("jszip")); const fs_extra_1 = __importDefault(require("fs-extra")); const path_1 = __importDefault(require("path")); const unzipper_1 = __importDefault(require("unzipper")); const promises_1 = require("stream/promises"); class Compressor { } _a = Compressor; Compressor.readDir = async (zip, dirPath) => { // 读取传入的文件目录 const files = await fs_extra_1.default.readdir(dirPath); for (let fileName of files) { const filePath = path_1.default.join(dirPath, fileName); const file = fs_extra_1.default.statSync(filePath); if (file.isDirectory()) { const dirZip = zip.folder(fileName); await _a.readDir(dirZip, filePath); } else { // 读取每个文件为 buffer 存到 zip 中 const buffer = await fs_extra_1.default.readFile(filePath); if (Buffer.byteLength(buffer)) { zip.file(fileName, buffer); } } } }; Compressor.zip = async (sourceDir, filename) => { const zip = new jszip_1.default(); await _a.readDir(zip, sourceDir); const buffer = await _a.zipBuffer(sourceDir); await fs_extra_1.default.writeFile(filename, buffer); }; Compressor.zipBuffer = async (sourceDir) => { const zip = new jszip_1.default(); await _a.readDir(zip, sourceDir); return zip.generateAsync({ type: 'nodebuffer', // 压缩类型 compression: 'DEFLATE', // 压缩算法 compressionOptions: { // 压缩级别 level: 9, }, }); }; Compressor.unzip = async (zipFilePath, targetDir) => { var _b; const readStream = await fs_extra_1.default.readFile(zipFilePath); const zip = await unzipper_1.default.Open.buffer(readStream); const entries = zip.files; const rootDir = ((_b = entries[0]) === null || _b === void 0 ? void 0 : _b.type) === 'Directory' ? path_1.default.basename(entries[0].path) : ''; for (const entry of entries) { const filePath = rootDir ? path_1.default.relative(rootDir, entry.path) : entry.path; const absolutePath = path_1.default.join(targetDir, filePath); const { type } = entry; if (type === 'Directory') { await fs_extra_1.default.mkdir(absolutePath, { recursive: true }); } else if (type === 'File') { await fs_extra_1.default.mkdir(path_1.default.dirname(absolutePath), { recursive: true }); const writeStream = fs_extra_1.default.createWriteStream(absolutePath); await (0, promises_1.pipeline)(entry.stream(), writeStream); } } }; exports.default = Compressor;