k.utils.compression
Gzip 解压与 ZIP 打包
概述
k.utils.compression 处理 Gzip 与 ZIP 归档(内存或站点文件路径)。
decompressGzip()
| 重载 | 说明 |
|---|---|
decompressGzip(path) | 从站点文件路径读取并解压为字符串 |
decompressGzipBinary(bytes) | 从字节数组解压 |
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
path | string | 是 | 站点文件路径 |
bytes | number[] | 是 | Gzip 字节数组 |
返回: string,按 UTF-8 解压后的文本。
ts
const text = k.utils.compression.decompressGzip("imports/catalog.json.gz")
const products = JSON.parse(text)
return {
count: products.length,
firstSku: products[0]?.sku
}如果 Gzip 内容来自上传文件或外部接口,直接传字节数组:
ts
const file = k.request.files[0]
const text = k.utils.compression.decompressGzipBinary(file.bytes)
return JSON.parse(text)zip()
| 重载 | 说明 |
|---|---|
zip(items) | items 为 { name, binary }[],返回 ZIP 字节 |
zip(folder, zipPath) | 将站点目录打包写入 zipPath |
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
items | { name: string, binary: number[] }[] | 是 | 要写入 ZIP 的文件列表 |
folder | string | 是 | 要打包的站点目录 |
zipPath | string | 是 | ZIP 文件保存路径 |
返回:
| 重载 | 返回 |
|---|---|
zip(items) | number[],ZIP 字节 |
zip(folder, zipPath) | void,直接写入站点文件 |
ts
const zipBytes = k.utils.compression.zip([
{
name: "readme.txt",
binary: k.utils.stringToBytes("Export generated by Kooboo", "utf-8")
},
{
name: "catalog.json",
binary: k.utils.stringToBytes(JSON.stringify(products), "utf-8")
}
])
k.file.writeBinary("exports/catalog.zip", zipBytes)打包整个站点文件夹时使用路径重载:
ts
k.utils.compression.zip("exports/catalog", "exports/catalog.zip")
const file = k.file.get("exports/catalog.zip")
return { path: file.fullName, size: file.size }unzip()
| 重载 | 说明 |
|---|---|
unzip(binary) | 解压为 ZipItem[](含 name、binary) |
unzip(zipPath, folder) | 解压到站点目录 |
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
binary | number[] | 是 | ZIP 字节 |
zipPath | string | 是 | 站点 ZIP 文件路径 |
folder | string | 是 | 解压目标目录 |
返回:
| 重载 | 返回 |
|---|---|
unzip(binary) | ZipItem[],包含 name、fullName、binary |
unzip(zipPath, folder) | void,直接写入站点目录 |
ts
const zipBytes = k.file.readBinary("imports/catalog.zip")
const items = k.utils.compression.unzip(zipBytes)
for (const item of items) {
k.file.writeBinary(`imports/unpacked/${item.fullName}`, item.binary)
}
return items.map(item => item.fullName)解压站点文件到目录:
ts
k.utils.compression.unzip("imports/catalog.zip", "imports/unpacked")
return k.file.folderFiles("imports/unpacked")