[英]How to compress a buffer with 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
的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
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.