类:zlib.ZipBuffer
🌐 Class: zlib.ZipBuffer
ZIP 压缩档案 API 是实验性的。第一次使用它的任何部分(包括这个类)都会发出实验性警告;仅仅导入 node:zlib 不会。
🌐 The ZIP archive API is experimental. Using any part of it (this class among
them) emits an experimental warning the first time; merely importing
node:zlib does not.
在内存中对已经存在于 Buffer、TypedArray、DataView 或 ArrayBuffer 的 ZIP 档案条目提供 零拷贝 的视图。它的条目集合可以编辑——可以添加或删除条目——但是,与 ZipFile 不同,这些修改 不会 写入源缓冲区:新添加的条目会作为独立的内存 ZipEntry 保存(传入的缓冲区是固定大小视图,无法追加内容),而删除操作只是从 ZipBuffer 的索引中移除条目。原始字节从未被修改。zipBuffer.toBuffer() 会将当前的条目集合序列化成一个新的档案。
🌐 An in-memory, zero-copy view over the entries of a ZIP archive already
held in a Buffer, TypedArray, DataView, or ArrayBuffer. Its set of
entries can be edited - entries added or removed - but, unlike ZipFile,
those edits are not written into the source buffer: a newly added entry is
held as a separate in-memory ZipEntry (the passed buffer is a fixed-size
view with no room to append to), and removal just drops the entry from
ZipBuffer's index. The original bytes are never modified.
zipBuffer.toBuffer() serializes the current set of entries into a fresh
archive.
ZipBuffer 不会复制你提供的归档文件。它只是保持对那块内存的一个视图,并且懒惰地、直接地读取每个条目的内容,这就是无论归档大小多大,构建都很便宜的原因。代价是,在 ZipBuffer 或从中获得的任何 ZipEntry 仍在使用时,你绝不能修改或重用那块内存——包括作为 TypedArray/DataView 支撑的 ArrayBuffer。如果源可能会被修改或重用,请传递一个副本(例如 Buffer.from(source))。
add() 和 toBuffer() 各自都有一个 *Sync 对应的版本(addSync(), toBufferSync()),它们会同步执行相同的压缩工作。就像同步的 node:fs API 一样,这些会阻塞 Node.js 的事件循环以及后续的 JavaScript 执行,直到操作完成;只在需要同步执行的情况下使用它们(例如短期运行的脚本或启动代码),不要在必须保持响应的代码中使用。
import { ZipBuffer } from 'node:zlib';
import { readFileSync, writeFileSync } from 'node:fs';
import { Buffer } from 'node:buffer';
const zip = new ZipBuffer(readFileSync('archive.zip'));
for (const [name, entry] of zip) {
console.log(name, entry.size);
}
await zip.add('hello.txt', Buffer.from('Hello, world!'));
zip.delete('unwanted.txt');
writeFileSync('archive.zip', await zip.toBuffer());const { ZipBuffer } = require('node:zlib');
const { readFileSync, writeFileSync } = require('node:fs');
async function main() {
const zip = new ZipBuffer(readFileSync('archive.zip'));
for (const [name, entry] of zip) {
console.log(name, entry.size);
}
await zip.add('hello.txt', Buffer.from('Hello, world!'));
zip.delete('unwanted.txt');
writeFileSync('archive.zip', await zip.toBuffer());
}
main();