2017-07-17 62 views
2

在Node.js的文件,我發現了一個句話說的Node.js,require.main ===模塊

當一個文件從Node.js的直接運行,require.main被設置爲它 模塊。這意味着可以通過測試require.main === module來確定文件是否已經直接運行。

我要問什麼是main這裏,我找不到這個main源代碼的定義,任何人都可以幫助,謝謝!

回答

6

require是一個函數。 .main是該功能的一個屬性,因此您可以參考require.main。你指的是文檔的那部分說,你可以寫這樣的代碼:

if (require.main === module) { 
    // this module was run directly from the command line as in node xxx.js 
} else { 
    // this module was not run directly from the command line and probably loaded by something else 
} 

在上面的代碼中module是傳遞到由node.js的加載,使所有代碼模塊的變量基本上如果require.main是當前模塊,那麼當前模塊是從命令行加載的內容。

設置該屬性的代碼在這裏:https://github.com/nodejs/node/blob/master/lib/internal/module.js#L23

+0

感謝您的回答,但我無法在module.js文件的Module.prototype.require中找到.main屬性。我只是對源代碼在哪裏定義.main屬性感到好奇。 – phaneven

+0

@phaneven - 設置該屬性的代碼位於:https://github.com/nodejs/node/blob/master/lib/internal/module.js#L23 – jfriend00