CodePark/ questions / File system & path
START PRACTICINGPRACTICE
Backend question · Node.js › File system & path

src/app.js contains fs.readFileSync("./config.json"). It works with node src/app.js run from src, but fails when run from the project root. Why?

Relative paths in fs resolve against process.cwd(), not against the file that contains the call

fs resolves relative paths from the process's current working directory, process.cwd(). This depends on the folder where you started Node, not on where the file is. From src, ./config.json points to src/config.json. From the project root, it points to config.json in the root, which doesn't exist.

require('./x') works differently: it resolves relative to the file that calls it.

To fix it, build the path from the module's own location:

• In CommonJS:
path.join(__dirname, 'config.json').
• In ESM: use
import.meta.dirname (Node 20.11 and later).

"
readFileSync only accepts absolute paths" is wrong: it accepts relative paths. That is why the code works when you run it from src.