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

Fab*_*ook 5 javascript node.js

我在这里有此代码:

if(fs.existsSync('./example/example.js')){
    cb(require('../example/example.js'));
}else{
    cb();
}
Run Code Online (Sandbox Code Playgroud)

为什么要fs.existSync使用与之不同的目录require

这将是目录树,排除不需要的东西...(我正在使用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);
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 5

您使用的路径require相对于您调用的文件require(相对于routes/index.js);您用于fs.existsSync()(以及其他fs功能)的路径是相对于当前工作目录的(该目录是您启动时当前的目录node,前提是您的应用程序未执行fs.chdir更改)。

至于这种差异的原因,我只能猜测,但这require是一种寻找其他模块的“额外”逻辑有意义的机制。如前所述,它也不应受到应用程序中运行时更改的影响fs.chdir


Ale*_*Trn 5

由于文件的相对路径是相对的process.cwd()如此链接中提到的。您可以使用path.resolve以下方法解析相对于该位置的路径:

const path = require('path');

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