[英]Why do require and fs.existSync use different relative paths
我在這里有此代碼:
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);
您用於require
的路徑是相對於您調用require
的文件的(相對於routes/index.js
); 用於fs.existsSync()
(和其他fs
函數)的路徑是相對於當前工作目錄的(該目錄是您啟動node
時的當前目錄),前提是您的應用程序不執行fs.chdir
進行更改它)。
至於這種差異的原因,我只能猜測,但是require
一種機制,對於這種機制,找到其他模塊的某些“額外”邏輯是有意義的。 它也不應受到應用程序中運行時更改的影響,例如上述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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.