javascript - 如何用 yazl 压缩缓冲区?
问题描述
如何通过 yazl 压缩/解压缩缓冲区? https://www.npmjs.com/package/yazl
我不想创建/保存一个 zip 文件,而只是压缩一个缓冲区并将其转发到另一个服务。任何示例代码都会有所帮助
var yazl = require("yazl");
var buf = fs.readFileSync(__dirname + '/testArchive.txt');
var zipfile = new yazl.ZipFile();
zipfile.addBuffer(buf, "TEMPENTRY");
zipfile.end();
那么此时是否已存档?那么如何使用 yauzl 为该缓冲区充气?
解决方案
这种功能应该会有所帮助,手动检索流的数据包,然后将它们连接成一个Buffer
:
function stream2buffer(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on('data', (chunk) => {
chunks.push(chunk);
}).on('end', () => {
resolve(Buffer.concat(chunks));
}).on('error', (err) => {
reject(err);
});
});
}
然后你可以在, 和另一端的回调yazl.ZipFile.outputStream
提供的可读流上使用它。yauzl.ZipFile.openReadStream
编辑
我的意思更像是在 yazl
's上使用此功能outputStream
,而不是在要压缩的源文件上。更像这样:
function zipper(mapping) { // mapping is expected to be a Map here
const handler = new yazl.ZipFile(); // yazl = require('yazl');
for (mapItem of mapping) {
if (typeof mapItem[1] === 'string' || mapItem[1] instanceof String) {
handler.addFile(mapItem[1], mapItem[0]);
} else if (mapItem[1] instanceof Buffer) {
handler.addBuffer(mapItem[1], mapItem[0]);
} else if (mapItem[1] instanceof stream.Readable) { // stream = require('stream');
handler.addReadStream(mapItem[1], mapItem[0]);
} else throw new Error('unsupported type');
}
handler.end();
return stream2buffer(handler.outputStream);
}
解压缩也是如此:
function unzipper(buffer) {
return new Promise((resolve, reject) => {
unzippedContents = {};
yauzl.fromBuffer(buffer, {lazyEntries: true}, (err, zip) => { // yauzl = require('yauzl')
if (err) return reject(err);
zip.on('entry', (entry) => {
if (/\/$/.test(entry.fileName)) return zip.readEntry(); // no directories
zip.openReadStream(entry, async (err, rs) => {
try {
if (err) throw err;
unzippedContents[entry.fileName] = await stream2buffer(rs);
} catch (err) {
zip.close();
return reject(err);
}
zip.readEntry();
});
}).on('end', () => {
zip.close();
resolve(unzippedContents);
});
zip.readEntry(); // start the process
});
});
}
推荐阅读
- java - Android:没有适配器附加
- python - Python 逻辑回归(PatsyError:模型缺少所需的结果变量)
- c++ - 河内塔程序中的堆栈泄漏
- python-3.x - 无法在 Visual Studio 代码中运行使用 kivy 和 python 制作的应用程序
- sql - 如何在 SQL Server 中使用逻辑运算符从字符串编写查询?
- javascript - php动态url变化
- xamarin - Xamarin 项目在部署到 App Store 时未应用一些更改
- encryption - Python:boto3解密
- reactjs - 如何使用 firebase 条带扩展添加多个订阅?
- powershell - Powershell 将文件夹内容移动到另一个文件夹