簡體   English   中英

為什么require和fs.existSync使用不同的相對路徑

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM