發表文章

目前顯示的是 10月, 2019的文章

[Node.js] require 的機制

最近在面試的時候, 寫了一些基本的題目, 但是卻有些地方是我自以為清楚, 但是不清楚的地方, 那就是這次要寫的 require! 其實一般人使用應該都會知道 require 完後, Node.js 會把 require 的物件, 會快取在記憶體內, 但是由於我真的太久沒寫, 所以在沒有理解的情況下, 也會忘記是不是真的每次 require 後就會存在記憶體中, 所以這次來分析一下原始碼 https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js // Loads a module at the given file path. Returns that module's // `exports` property. Module.prototype.require = function(id) { validateString(id, 'id'); if (id === '') { throw new ERR_INVALID_ARG_VALUE('id', id, 'must be a non-empty string'); } requireDepth++; try { return Module._load(id, this, /* isMain */ false); } finally { requireDepth--; } }; 從上面就可以看出, 關鍵是在 Module._load 那我們再看一下 Module._load 的程式碼 // Check the cache for the requested file. // 1. 假如一個 module 已經存在快取中, 直接返回其 exports 的物件 // 2. 假如 module 是原生系統內部的 module (ex: file, path), // 呼叫 NativeModule.prototype.compileForPublicLoader() 並且返回其 exports