On this page
@std/tar
Unstable
This @std package is experimental and its API may change without a major version bump.
Overview Jump to heading
Streaming utilities for working with tar archives.
Files are not compressed, only collected into the archive.
import { UntarStream } from "@std/tar/untar-stream";
import { dirname, normalize } from "@std/path";
for await (
const entry of (await Deno.open("./out.tar.gz"))
.readable
.pipeThrough(new DecompressionStream("gzip"))
.pipeThrough(new UntarStream())
) {
const path = normalize(entry.path);
await Deno.mkdir(dirname(path), { recursive: true });
await entry.readable?.pipeTo((await Deno.create(path)).writable);
}
Add to your project Jump to heading
deno add jsr:@std/tar
See all symbols in @std/tar on
什么是 tar? Jump to heading
Tar(磁带归档)是一种广泛使用的文件格式,用于将多个文件收集到单个归档文件中,通常方便分发或备份。它保留文件的元数据,如权限和时间戳,使其适用于系统备份和软件发布。
为什么使用 @std/tar? Jump to heading
使用此包可以以流式方式创建或提取 tar 归档,这对于大型数据集效率更高,且避免了大量内存使用。
- 本模块以流为先:使用 Web Streams 来读取/写入条目,无需缓冲整个归档。
- 安全性:在写入磁盘前会清理条目路径,防止路径遍历(".." 段)。
- Tar 是归档格式,不是压缩格式。可叠加使用
CompressionStream/DecompressionStream来处理 gzip。 - 提取时如果头部包含权限或修改时间,则会保留,确保文件信息的准确性。
示例 Jump to heading
import { UntarStream } from "@std/tar/untar-stream";
import { dirname, isAbsolute, normalize } from "@std/path";
const outDir = "/safe/root";
for await (const entry of file.readable.pipeThrough(new UntarStream())) {
const normalized = normalize(entry.path);
// 防止写出到 outDir 之外
if (normalized.includes("..") || isAbsolute(normalized)) continue;
const dest = `${outDir}/${normalized}`;
await Deno.mkdir(dirname(dest), { recursive: true });
if (entry.readable) {
await entry.readable.pipeTo((await Deno.create(dest)).writable);
}
}