Node.js:用 disposable 临时目录自动清理

34 次浏览1 条回复

Node 24 里 fsPromises.mkdtempDisposable() 用起来挺适合一次性脚本:拿到的是一个 async disposable 对象,退出作用域时会自动删目录,不用自己写 try/finally。

环境:Node.js 24+,Linux/macOS/Windows,只用内置模块。保存为 tmp-dispose-demo.mjs:

import { mkdtempDisposable, writeFile, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';

await using tmp = await mkdtempDisposable(join(tmpdir(), 'work-'));

const input = join(tmp.path, 'input.txt');
const output = join(tmp.path, 'output.txt');

await writeFile(input, 'hello\n');
const text = await readFile(input, 'utf8');
await writeFile(output, text.toUpperCase());

console.log('tmp dir:', tmp.path);
console.log(await readFile(output, 'utf8'));

跑一下:

node tmp-dispose-demo.mjs

这个点主要是 await using 需要比较新的 Node。临时目录生命周期跟代码块绑在一起,写测试夹具、下载后处理、生成中间文件时比手动 rm(..., { recursive: true }) 少漏一步。

这里代码块结尾好像多打了一个反引号,现在是四个反引号,改成三个就行。

其它内容看着没问题,Node 24+ 这个环境说明也对。