Deno调试时读取文件报NotFound(os error 2),为何运行正常?
Deno调试时找不到文件的问题排查与解决
我在test.ts中编写了如下代码:
const text = await Deno.readTextFile("a.md"); console.log(text);
使用deno run --allow-read .\test.ts命令运行时一切正常,但使用调试器时却抛出错误:
error: Uncaught NotFound: The system cannot find the file specified. (os error 2): readfile 'a.md' const text = await Deno.readTextFile("a.md"); ^
我的launch.json配置内容如下:
{ "version": "0.2.0", "configurations": [ { "request": "launch", "name": "Deno", "type": "node", "program": "${file}", "cwd": "${workspaceFolder}", "runtimeExecutable": "deno", "runtimeArgs": [ "run", "--allow-read" ], "attachSimplePort": 9229 } ] }
问题原因
调试时找不到a.md的核心原因有两个:
- 调试配置的
type字段错误:使用了node类型而非Deno专属调试类型,导致调试器的工作目录处理逻辑不符合Deno预期。 - 工作目录匹配问题:如果
test.ts不在${workspaceFolder}目录下,相对路径a.md的解析基准会和命令行运行时不一致,导致文件找不到。
解决步骤
- 修正调试类型:将
launch.json中的type字段从node改为deno,这是适配Deno调试的关键配置。 - 调整工作目录(按需):
- 若
test.ts和a.md都在项目根目录(${workspaceFolder}),保持cwd配置不变; - 若
test.ts在子目录,将cwd改为${fileDirname},让调试器以当前文件所在目录为工作基准,确保相对路径解析正确。
- 若
修改后的launch.json(项目根目录场景)
{ "version": "0.2.0", "configurations": [ { "request": "launch", "name": "Deno", "type": "deno", "program": "${file}", "cwd": "${workspaceFolder}", "runtimeExecutable": "deno", "runtimeArgs": [ "run", "--allow-read" ], "attachSimplePort": 9229 } ] }
子目录场景的cwd配置
"cwd": "${fileDirname}"
额外验证
- 可以在
test.ts中添加console.log(Deno.cwd()),调试时打印当前工作目录,核对a.md是否存在于该路径下; - 确保VS Code打开的是完整项目工作区,而非单独打开
test.ts文件。
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

