Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do require and fs.existSync use different relative paths

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);
like image 474
FabianCook Avatar asked May 20 '13 07:05

FabianCook


1 Answers

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.

like image 86
robertklep Avatar answered Oct 24 '22 02:10

robertklep