【问题标题】:error while reading json file using fs in Node js在Node js中使用fs读取json文件时出错
【发布时间】:2020-12-11 17:36:53
【问题描述】:

我正在为 node JS 和 Express 开发一个 3 层架构后端。

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

我的问题是从 fs.readFile 抛出的错误没有被传播到上层,尽管使用了 throw。但是该代码适用于 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)

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

非常感谢任何帮助

【问题讨论】:

    标签: node.js express error-handling fs


    【解决方案1】:

    这是因为错误是在回调中抛出的。该错误不会从您的服务中的 catch 块中捕获(请查看 this article,其中详细说明了这一点)。不过,您可以使用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 拒绝,现在将在您的服务中捕获错误。

    还有一点:从模块中导出实例被认为是不好的做法,请参阅this 了解更多信息。

    【讨论】:

    • 您好,感谢您的帮助。使用上面的方法给我一个消息 ""message": "ENOENT: no such file or directory, open 'C:\\Users\\harsh\\CB\\Node JS Hands On Lab\\BE\\products.json '”在消息字段中作为响应。我正在寻找“错误读取文件”作为消息字段。我想知道使用 readFile() 方法实现此目的的正确方法,但感谢您的帮助。另外,我有整个后端的单个 Service 和 DAO 实例(单例模式),所以我直接导出了实例。
    • 您始终可以从readFile 捕获错误并抛出您的自定义执行。我会编辑答案。
    • 谢谢,我会将此标记为已接受。无论如何我们可以使用默认的 fs.readFile() 并实现相同的目标?
    • 有一种方法:如果读取文件成功/失败,您可以将默认 fs.readFile 包装在自己的承诺中,并从回调中解决/拒绝它。但是由于节点已经为您提供了承诺版本,所以它没有多大意义:)
    • 只有通过将fs.readFile 包装在一个承诺中的描述方式,但try/await/catch 基本上是在做同样的事情。我鼓励您阅读此内容:itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a 它解释得很好。
    猜你喜欢
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2016-11-27
    • 2016-06-23
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多