2013-05-20 82 views
2

我有这样的代码在这里:为什么需要和fs.existSync使用不同的相对路径

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

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

这将是不包括的东西不需要目录树......(我用快递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); 
+0

我不明白'接近'票,我认为这是一个适当的问题。 – robertklep

+0

这是一个正确的问题-.- – FabianCook

回答

3

您使用require的路径是相对于您拨打require文件(所以相对到routes/index.js);您为fs.existsSync()(和其他fs函数)使用的路径相对于当前工作目录(如果您的应用不执行fs.chdir来更改该目录,则该目录是当您启动node时最新的目录)。

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

相关问题