为什么require和fs.existSync使用不同的相对path
我在这里有这个代码:
if(fs.existsSync('./example/example.js')){ cb(require('../example/example.js')); }else{ cb(); }
为什么fs.existSync
需要使用不同的目录?
这将是目录树排除不需要的东西…(我正在使用快递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
的path相对于您调用require
的文件(相对于routes/index.js
); 用于fs.existsSync()
(和其他fs
函数)的path与当前工作目录(当您启动node
时是当前目录)相关,前提是您的应用程序不执行fs.chdir
以更改它)。
至于这个差别的原因,我只能猜测,但是require
是一个“额外的”逻辑寻找其他模块的机制是合理的。 它也不应该受到应用程序运行时变化的影响,如前面提到的fs.chdir
。