I have this code here:
if(fs.existsSync('./example/example.js')){
cb(require('../example/example.js'));
}else{
cb();
}
Why should fs.existSync
be using a different directory than require
?
This would be the directory tree excluding things not needed... (I am using express btw)
\example
example.js
\routes
index.js <-- this is the one where I am using this code
app.js <-- this one requires index.js and calls its functions using app.get('/example',example.index);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With