You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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的核心原因有两个:

  1. 调试配置的type字段错误:使用了node类型而非Deno专属调试类型,导致调试器的工作目录处理逻辑不符合Deno预期。
  2. 工作目录匹配问题:如果test.ts不在${workspaceFolder}目录下,相对路径a.md的解析基准会和命令行运行时不一致,导致文件找不到。

解决步骤

  1. 修正调试类型:将launch.json中的type字段从node改为deno,这是适配Deno调试的关键配置。
  2. 调整工作目录(按需):
    • 若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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:06:04