Fab*_*ook 5 javascript node.js
我在这里有此代码:
if(fs.existsSync('./example/example.js')){
cb(require('../example/example.js'));
}else{
cb();
}
Run Code Online (Sandbox Code Playgroud)
为什么要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);
Run Code Online (Sandbox Code Playgroud)
由于文件的相对路径是相对的process.cwd(),如此链接中提到的。您可以使用path.resolve以下方法解析相对于该位置的路径:
const path = require('path');
const desiredPath = path.resolve(__dirname, './file-location');
console.log(fs.existsSync(desiredPath)); // returns true if exists
Run Code Online (Sandbox Code Playgroud)