Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fs.readFileSync says 'no such file or directory' although require() returns the file correctly

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

You’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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading