Why do require and fs.existSync use different relative paths
The path you use for require
is relative to the file in which you call require
(so relative to routes/index.js
); the path you use for fs.existsSync()
(and the other fs
functions) is relative to the current working directory (which is the directory that was current when you started node
, provided that your app doesn't execute fs.chdir
to change it).
As for the reason of this difference, I can only guess, but require
is a mechanism for which some 'extra' logic w.r.t. finding other modules makes sense. It should also not be influenced by runtime changes in the application, like the aforementioned fs.chdir
.
Since the relative path to a file is relative to process.cwd(), as mentioned in this link. You can use path.resolve
to resolve the path relative to the location as below:
const path = require('path');
const desiredPath = path.resolve(__dirname, './file-location');
console.log(fs.existsSync(desiredPath)); // returns true if exists