【问题标题】:fs.readFileSync says 'no such file or directory' although require() returns the file correctlyfs.readFileSync 说“没有这样的文件或目录”,尽管 require() 正确返回了文件
【发布时间】:2022-01-30 05:15:06
【问题描述】:

我需要动态读取 JSON 文件。这就是为什么require() 不会削减它的原因。在 NodeJS 服务器重新启动之前,它不会简单地更新文件。这就是为什么我必须使用fs.readFilefs.readFileSync

当我使用时,const data = require("../data.json"); 它只是正确读取它。完全没有问题,但就像我说的,它不会动态更新。

当我使用const data = () => fs.readFileSync("../data.json", { encoding: "utf8" }); 时,它只会返回Error: ENOENT: no such file or directory, open '../data.json'

我也试过fs.readFile。没用。

最奇怪的是,当我尝试使用 fs.readFileSync 读取另一个 json 文件时,我看到了我几天前更改的值。它读取旧版本。我不明白。那个旧版本已经不存在了。我手动检查了。

我试过npm installnpm cache clean --force。我想不出别的了。

【问题讨论】:

  • 使用绝对路径,以确保 CWD 没有问题。

标签: javascript node.js json


【解决方案1】:

如果您在 Node.js 中使用 CommonJS 模块,您可能正在寻找 require.resolve。这将使用require 的内部结构为您要读取的文件提供绝对路径字符串。

来源:https://nodejs.org/api/modules.html#requireresolverequest-options

【讨论】:

  • const data = () => fs.readFileSync(require.resolve("../data.json"), { encoding: "utf8" }); 这解决了问题。谢谢。
  • 感谢您的帮助,这也解决了我的问题
【解决方案2】:

require 采用相对于模块文件所在目录的路径。

readFileSync 采用相对于当前工作目录的路径。

这些对你来说一定是不同的。

考虑将path.resolve 与您的相对路径和__dirname 一起使用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2013-09-26
    • 1970-01-01
    相关资源
    最近更新 更多