简体   繁体   English

为什么require和fs.existSync使用不同的相对路径

[英]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 ? 为什么fs.existSync应该使用与require不同的目录?

This would be the directory tree excluding things not needed... (I am using express btw) 这将是目录树,排除不需要的东西...(我正在使用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 ); 您用于require的路径是相对于您调用require的文件的(相对于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). 用于fs.existsSync() (和其他fs函数)的路径是相对于当前工作目录的(该目录是您启动node时的当前目录),前提是您的应用程序不执行fs.chdir进行更改它)。

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. 至于这种差异的原因,我只能猜测,但是require一种机制,对于这种机制,找到其他模块的某些“额外”逻辑是有意义的。 It should also not be influenced by runtime changes in the application, like the aforementioned fs.chdir . 它也不应受到应用程序中运行时更改的影响,例如上述fs.chdir

Since the relative path to a file is relative to process.cwd(), as mentioned in this link . 由于文件的相对路径是相对于process.cwd()的,因此如本链接所述 You can use path.resolve to resolve the path relative to the location as below: 您可以使用path.resolve来解析相对于位置的路径,如下所示:

const path = require('path');

const desiredPath = path.resolve(__dirname, './file-location');
console.log(fs.existsSync(desiredPath)); // returns true if exists

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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