https://github.com/archiverjs/node-archiver/issues/476
文件可以上传,文件也可以下载 系统默认打开有问题,BandZip 损坏,但是文件依旧可以看到打开
可能就是压缩同步异步之间的 Bug
import fs from 'fs';
import archiver from 'archiver';
import path from 'path';
import { utilLogger } from './winstonLogUtil';
import { BufferFileInfo } from '../../../typings/publish';
import { sleep } from './objectUtils';
import { isDev } from './envUtil';
// 异步函数,将多个Buffer合并并保存到本地
export async function compressBuffersToDisk (bufferList: BufferFileInfo[] | any, outputPath) {
try {
const archive = archiver('zip', { zlib: { level: 1 }, directory: false }); // 使用最高压缩级别
// 如果对应路径不存在,自动创建一个文件夹
if (!fs.existsSync(process.env.LOCAL_SAVE_DIR)) {
fs.mkdirSync(process.env.LOCAL_SAVE_DIR);
}
outputPath = path.join(process.env.LOCAL_SAVE_DIR, outputPath);
// 创建输出流并将其绑定到输出文件
const output = fs.createWriteStream(outputPath);
// 将archive的输出流连接到文件输出流
archive.pipe(output);
if (bufferList instanceof Array) {
bufferList.forEach(bufferInfo => {
archive.append(bufferInfo.data, { name: bufferInfo.fileName });
});
} else {
Object.entries(bufferList).forEach(([fileName, buffer]) => {
archive.append(buffer, { name: fileName });
});
}
// 完成压缩并关闭输出流 必须要有
await archive.finalize();
// 。。。本地等待 1 秒,否则上传 oss 然后再下载下来打不开报错(用专业 zip 可以打开,但仍然提示报错)
// 其他环境是网络延迟消息传递导致延迟,基本不会报这个错
if (isDev()) {
await sleep(1000);
}
return outputPath;
} catch (error) {
utilLogger.error(`【压缩过程中出现错误】fileUtils ${error.message}`);
return false;
}
}
export interface BufferFileInfo {
fileName: string;
data: Buffer;
}
const saveZipBufferData = {
'image.png': orgin_image,
'mask_image.png': Buffer.from(await (await getImageFileFromAnyObj(maskImage)).arrayBuffer()),
'refer_image.png': orgin_image,
};
---
import fs from 'fs';
import archiver from 'archiver';
import path from 'path';
import { utilLogger } from './winstonLogUtil';
import { BufferFileInfo } from '../../../typings/publish';
// 异步函数,将多个Buffer合并并保存到本地
export async function compressBuffersToDisk (bufferList: BufferFileInfo[] | any, outputPath): Promise<string> {
return new Promise((resolve, reject) => {
try {
const archive = archiver('zip', { zlib: { level: 1 }, directory: false }); // 使用最高压缩级别
// 如果对应路径不存在,自动创建一个文件夹
if (!fs.existsSync(process.env.LOCAL_SAVE_DIR)) {
fs.mkdirSync(process.env.LOCAL_SAVE_DIR);
}
outputPath = path.join(process.env.LOCAL_SAVE_DIR, outputPath);
// 创建输出流并将其绑定到输出文件
const output = fs.createWriteStream(outputPath);
// 将archive的输出流连接到文件输出流
archive.pipe(output);
if (bufferList instanceof Array) {
bufferList.forEach(bufferInfo => {
archive.append(bufferInfo.data, { name: bufferInfo.fileName });
});
} else {
Object.entries(bufferList).forEach(([fileName, buffer]) => {
archive.append(buffer, { name: fileName });
});
}
output.on('close', () => {
resolve(outputPath);
});
archive.on('error', (err: Error) => {
reject(err);
});
// 完成压缩并关闭输出流
archive.finalize();
} catch (error) {
utilLogger.error(`【压缩过程中出现错误】fileUtils ${error.message}`);
reject(error);
}
});
}