在 "Deno.readFile Method()" 下出现错误

Getting error under "Deno.readFile Method()"

我在学习Deno我是初学者,里面get.js我报错,请大神解释一下 什么这里出错了?我收到一条错误消息,我在 responseDeno 下收到一条错误消息。我在下面提供了所有的编码,请任何人帮助我!

这是我的控制台输出

D:\Deno Documentation\deno4>deno run --allow-net --allow-read --allow-write .\index.js
http:/localhost:3000
NotFound: The system cannot find the path specified. (os error 3)
    at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
    at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
    at async Object.open ($deno$/files.ts:37:15)
    at async Object.readFile ($deno$/read_file.ts:13:16)
    at async default (file:///D:/Deno%20Documentation/deno4/controllers/todos/get.js:9:20)
    at async Application.#handleRequest (https://deno.land/x/oak@v4.0.0/application.ts:187:9)

我在网站上的输出

index.js

import {Application} from 'https://deno.land/x/oak@v4.0.0/mod.ts';

import {PORT} from './config.js';

import router from './router.js';

const app=new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`http:/localhost:${PORT}`);

await app.listen({port: PORT});

router.js

import {Router} from 'https://deno.land/x/oak@v4.0.0/mod.ts';
import getTodos from './controllers/todos/get.js';

const router=new Router();

router.get('/',({response})=>
{
    response.body="This API is Working";
});

router.get('/todos',getTodos);

export default router;

config.js

export const PORT=3000;
export const FILE_PATH='./data/todos.json'; 

get.js

import {FILE_PATH} from '../../config.js';

export default async({ response })=>
{

    const decoder=new TextDecoder();

    try {
        const data=await Deno.readFile(FILE_PATH);
        const todos=JSON.parse(decoder.decode(data));

        console.log(data);

        response.status=200;
        response.body={status: 'success',todos};

    } catch (error) {
        response.status=500;
        response.body={status: 'failed',todos:[]};
    }
} 

todos.json

[
    {"id":1,"title":"title 1","completed":true},
    {"id":2,"title":"title 2","completed":false},
    {"id":3,"title":"title 3","completed":true}
]

提交堆栈跟踪后的更新:

错误提示您文件不存在。提供 Deno.readFile

的有效文件路径

旧答案

您正在读取的文件不包含有效的 JSON,很可能是因为您还没有添加 TODO

在调用 JSON.parse 之前,您必须检查 data 是否为空。或者您可以在 JSON.parse 周围添加一个 try/catch 并默认为空待办事项。

export default async ({ response }) => {
  const decoder = new TextDecoder();

  try {
    const data = await Deno.readFile(FILE_PATH);
    let todos = [];
    try {
        todos = JSON.parse(decoder.decode(data));
    } catch(e) {
        // invalid JSON, most likely empty file
    }

    console.log(data);

    response.status = 200;
    response.body = { status: "success", todos };
  } catch (error) {
    response.status = 500;
    response.body = { status: "failed", todos: [] };
  }
};