简体   繁体   中英

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);

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 wrt 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM