Deno中FsFile.readable流耗尽时是否自动关闭文件?
Deno中FsFile.readable流耗尽时是否自动关闭文件?
先看你给出的代码:
const file = await Deno.open(fsPathname, { read: true }) return new Response(file.readable, { status: 200 })
答案:不会自动关闭文件,这点当前Deno官方文档确实未明确提及。
如果不想做额外复杂操作,有两种简洁的解决方式:
- 利用流的回调自动关闭:
const file = await Deno.open(fsPathname, { read: true }); const res = new Response(file.readable, { status: 200 }); // 流结束或取消时关闭文件 res.body?.cancel().finally(() => file.close()); return res;
- 使用Deno 1.28+支持的
using声明(推荐):
await using file = await Deno.open(fsPathname, { read: true }); return new Response(file.readable, { status: 200 });
using会在代码块执行完毕后自动调用file.close(),无需手动处理,语法更简洁。
内容的提问来源于stack exchange,提问作者Chris_F
相关产品推荐
相关产品推荐

