admin管理员组文章数量:1197764
I need to read a JSON file dynamically. This is why require()
won't cut it. It doesn't simply update the file until NodeJS server restarts. This is why I have to use fs.readFile
or fs.readFileSync
.
When I use, const data = require("../data.json");
it just reads it properly. No issues at all, but like I said, it doesn't update dynamically.
When I use const data = () => fs.readFileSync("../data.json", { encoding: "utf8" });
it simply returns Error: ENOENT: no such file or directory, open '../data.json'
I also tried fs.readFile
. Doesn't work.
Most weirdly, when I try to read another json file with fs.readFileSync
, I'm seeing values that I changed days ago. It reads an old version. I don't understand. That old version doesn't exist anymore. I manually checked.
I tried npm install
, npm cache clean --force
. I can't think of anything else.
I need to read a JSON file dynamically. This is why require()
won't cut it. It doesn't simply update the file until NodeJS server restarts. This is why I have to use fs.readFile
or fs.readFileSync
.
When I use, const data = require("../data.json");
it just reads it properly. No issues at all, but like I said, it doesn't update dynamically.
When I use const data = () => fs.readFileSync("../data.json", { encoding: "utf8" });
it simply returns Error: ENOENT: no such file or directory, open '../data.json'
I also tried fs.readFile
. Doesn't work.
Most weirdly, when I try to read another json file with fs.readFileSync
, I'm seeing values that I changed days ago. It reads an old version. I don't understand. That old version doesn't exist anymore. I manually checked.
I tried npm install
, npm cache clean --force
. I can't think of anything else.
- Use an absolute path so you're sure it's not an issue with CWD. – jsejcksn Commented Jan 29, 2022 at 21:11
2 Answers
Reset to default 12You're probably looking for require.resolve
if you're working with CommonJS modules in Node. This will use the internals of require
to provide the absolute path string to the file you want to read in.
Source: https://nodejs.org/api/modules.html#requireresolverequest-options
require
takes a path relative to the directory the module file is in.
readFileSync
takes a path relative to the current working directory.
These must be different for you.
Consider using path.resolve
with your relative path and __dirname
本文标签:
版权声明:本文标题:javascript - fs.readFileSync says 'no such file or directory' although require() returns the file correctly - St 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738561156a2099257.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论