在 Node js 中使用 fs 读取 json 文件时出错

error while reading json file using fs in Node js

我正在为节点 JS 和 Express 开发 3 层架构后端。

我必须读取包含 JSON 数据的文件并使用 REST

使用 HTTP 发送

我的问题是,尽管使用了 throw,但从 fs.readFile 抛出的错误并没有传播到上层。但是代码适用于 fs.readFileSync.

dao.js

const fs = require("fs");

class DAO {
    async getAllProducts() {
        // try {
        //  fs.readFileSync("products.json");
        // } catch (error) {
        //  throw new Error("Error Reading File");
        // }
        fs.readFile("./products.json", (err, data) => {
            if (err) {
                throw new Error("Error Reading File");
            } else {
                let d = JSON.parse(data);
                return d;
            }
        });
    }
}

module.exports = new DAO();

service.js

const dao = require("../data/dao");

class Service {
    async getAllProducts() {
        try {
            return await dao.getAllProducts();
        } catch (error) {
            throw error;
        }
    }
}

module.exports = new Service();

product.js

const express = require("express");
const router = express.Router();
const service = require("../service/service");
const Response = require("../models/Response");

router.get("/", async (req, res) => {
    try {
        const data = await service.getAllProducts();
        res.status(200).send(new Response(200, "Success", null, data));
    } catch (error) {
        res.status(500).send(new Response(500, "Failure", error.message, null));
    }
});

module.exports = router;

点击 http://localhost:3000/api/products 并使用 fs.readFileSync 方法后,o/p 符合预期

{
    "statusCode": 500,
    "status": "Failure",
    "message": "Error Reading File",
    "data": null
}

但是在使用 fs.readFile 时 o/p 很奇怪

{
    "statusCode": 200,
    "status": "Success",
    "message": null
}

控制台输出如下

                                throw new Error("Error Reading File");
                                ^

Error: Error Reading File
    at ReadFileContext.callback (C:\Users\a\b\c\d\data\dao.js:12:11)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:264:13)

我的猜测是因为读取文件是一个异步 fn,所以它导致了问题,但为了解决这个问题,我在所有地方都使用了 async/await,所以应该不会有问题。不知道哪里出错了。

非常感谢任何帮助

那是因为错误是在回调中抛出的。该错误不会从您的服务中的 catch 块中捕获(检查 this article 详细解释了这一点)。除了使用回调和同步 read-operation,您还可以使用 fs 的承诺:

async getAllProducts() {
     try {        
        const data = await fs.promises.readFile("./products.json");
        return JSON.parse(data);
     } catch (err) {
        console.log(err); // print the orig error but throw your custom error
        throw new Error("Error Reading File");
     }
}

如果 readFile 拒绝,错误现在将在您的服务中被捕获。

还有一件事:从模块导出实例被认为是不好的做法,有关详细信息,请参阅