Javascript 为什么require和fs.existSync使用不同的相对路径
我这里有这个代码:Javascript 为什么require和fs.existSync使用不同的相对路径,javascript,node.js,Javascript,Node.js,我这里有这个代码: if(fs.existsSync('./example/example.js')){ cb(require('../example/example.js')); }else{ cb(); } 为什么fs.existSync应该使用与require不同的目录 这将是目录树,不包括不需要的内容。。。(我正在使用快速btw) \example example.js \路线 index.js用于require的路径相对于调用require的文件(因此相对于route
if(fs.existsSync('./example/example.js')){
cb(require('../example/example.js'));
}else{
cb();
}
为什么fs.existSync
应该使用与require
不同的目录
这将是目录树,不包括不需要的内容。。。(我正在使用快速btw)
\example
example.js
\路线
index.js用于require
的路径相对于调用require
的文件(因此相对于routes/index.js
);您用于fs.existsSync()
(以及其他fs
函数)的路径相对于当前工作目录(即启动节点时的当前目录,前提是您的应用程序不执行以对其进行更改)
至于这种差异的原因,我只能猜测,但是require
是一种机制,对于这种机制,一些“额外”逻辑w.r.t.寻找其他模块是有意义的。它也不应该受到应用程序中运行时更改的影响,如前面提到的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
我不理解“接近”的投票,我认为这是一个恰当的问题。这是一个恰当的问题--
const path = require('path');
const desiredPath = path.resolve(__dirname, './file-location');
console.log(fs.existsSync(desiredPath)); // returns true if exists