繁体   English   中英

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

[英]Why do require and fs.existSync use different relative paths

我在这里有此代码:

if(fs.existsSync('./example/example.js')){
    cb(require('../example/example.js'));
}else{
    cb();
}

为什么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);

您用于require的路径是相对于您调用require的文件的(相对于routes/index.js ); 用于fs.existsSync() (和其他fs函数)的路径是相对于当前工作目录的(该目录是您启动node时的当前目录),前提是您的应用程序不执行fs.chdir进行更改它)。

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

由于文件的相对路径是相对于process.cwd()的,因此如本链接所述 您可以使用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