临时文件 & 目录
临时文件和目录用于存储不打算永久保存的数据。例如,作为下载数据的本地缓存。
`Deno.makeTempFile()` 函数在默认临时目录中创建临时文件,并返回文件路径。
const tempFilePath = await Deno.makeTempFile();
console.log("Temp file path:", tempFilePath);
await Deno.writeTextFile(tempFilePath, "Hello world!");
const data = await Deno.readTextFile(tempFilePath);
console.log("Temp file data:", data);
可以为临时文件指定自定义前缀和后缀。
const tempFilePath2 = await Deno.makeTempFile({
prefix: "logs_",
suffix: ".txt",
});
console.log("Temp file path 2:", tempFilePath2);
创建临时文件的目录也可以自定义。这里我们使用相对路径 `./tmp` 目录。
await Deno.mkdir("./tmp", { recursive: true });
const tempFilePath3 = await Deno.makeTempFile({
dir: "./tmp",
});
console.log("Temp file path 3:", tempFilePath3);
也可以创建一个临时目录。
const tempDirPath = await Deno.makeTempDir();
console.log("Temp dir path:", tempDirPath);
它与 `makeTempFile()` 具有相同的前缀、后缀和目录选项。
const tempDirPath2 = await Deno.makeTempDir({
prefix: "logs_",
suffix: "_folder",
dir: "./tmp",
});
console.log("Temp dir path 2:", tempDirPath2);
上述函数的同步版本也可用。
const tempFilePath4 = Deno.makeTempFileSync();
const tempDirPath3 = Deno.makeTempDirSync();
console.log("Temp file path 4:", tempFilePath4);
console.log("Temp dir path 3:", tempDirPath3);
使用 Deno CLI 在本地运行此示例
deno run -R -W https://docs.deno.org.cn/examples/scripts/temporary_files.ts