8

我在这里有这段代码:

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

2 回答 2

7

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

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

于 2013-05-20T08:12:19.807 回答
4

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

const path = require('path');

const desiredPath = path.resolve(__dirname, './file-location');
console.log(fs.existsSync(desiredPath)); // returns true if exists
于 2019-10-20T06:36:20.260 回答