DIV CSS 佈局教程網

Node.js 中 require 模組載入機制完整解析
編輯:關於JavaScript     

Node.js 之所以能以模組化的方式組織後端程式碼,靠的就是全域的 require() 函式。它接受一個參數,可以是帶有完整路徑的檔案名稱,也可以只是一個模組名稱;若要載入 Node 內建的模組,直接寫模組名即可。下面的範例展示了最基礎的用法。

建立並載入自訂模組

先建立 2.js:

var name = "思思博士";
exports.name = name;

再建立 1.js:

var two = require("./2.js");
console.log(two.name);
// 輸出結果:思思博士

主模組的判定

在 Node 中,所有腳本檔案都是模組檔案。如果某個模組是透過命令列 node 指令直接執行的,它就會被視為應用程式的主模組。可以用下面的方式判斷目前檔案是否為主模組:

if (module === require.main) {
  console.log("當前模組是主模組");
}
// 輸出結果:當前模組是主模組

模組只會被執行一次

2.js 的內容:

var name = "思思博士";
console.log(name);
exports.name = name;

1.js 的內容:

var two  = require("./2.js");
var two1 = require("./2.js");
// 雖然 require 了兩次,但 console.log(name) 只會輸出一次。

這是因為 Node 會把首次載入的結果放入快取,後續的 require 直接回傳快取中的 exports 物件,不會重新執行模組內的程式碼。

require.resolve():查詢模組的絕對路徑

var url = require.resolve("./2");
console.log(url);
// 輸出結果:E:\node\gys\2.js

require.cache:已載入模組的快取區

這個屬性代表所有已被載入模組的快取,結構大致如下:

{
  'E:\\node\\gys\\1.js': {
    id: '.',
    exports: {},
    parent: null,
    filename: 'E:\\node\\gys\\1.js',
    loaded: false,
    children: [ [Object] ],
    paths: [ 'E:\\node\\gys\\node_modules',
             'E:\\node\\node_modules',
             'E:\\node_modules' ]
  },
  'E:\\node\\gys\\2.js': {
    id: 'E:\\node\\gys\\2.js',
    exports: { name: '思思博士' },
    parent: { /* 1.js 的模組物件 */ },
    filename: 'E:\\node\\gys\\2.js',
    loaded: true,
    children: [],
    paths: [ 'E:\\node\\gys\\node_modules',
             'E:\\node\\node_modules',
             'E:\\node_modules' ]
  }
}

用 delete 清除快取,強制重新執行

刪除快取區中的模組物件後,下一次載入該模組時,Node 會重新執行模組內的程式碼:

var two  = require("./2.js");
var two1 = require("./2.js");
console.log("刪除前");
delete require.cache[require.resolve("./2.js")];
console.log("刪除後");
var two2 = require("./2.js");

/*
 * 輸出結果:
 * 思思博士
 * 刪除前
 * 刪除後
 * 思思博士
 */

掌握以上幾個要點,就能理解 Node.js 中 require 的運作方式了。若有疑問,歡迎留言討論。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved