Q. Node.js Module 運作機制

Node.js 環境中, 利用 require()取得的module, 如果是同一檔案, 將會回傳同一 Object. 當同一檔案(module)被require()多次時, 所有的Instances 將會指向同一個Object

This means (among other things) that every call to require(‘foo’) will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require(‘foo’) may not cause the module code to be executed multiple times. This is an important feature. With it, “partially done” objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.

Q. module.exports

模組是包裝程式碼與指定它的命名空間的機制

模組可以匯出任何型態的值. 比如說, 匯出一個函式

function calculate(r) {
    // do something
}

module.exports = calculate;

如果希望模組裡的函式不只一個, 可以匯出物件

// amanda.js
module.exports = {
    fanc_1(a, b) {
        // do something
    },
    fanc_2(c) {
        // do something
    },
    fanc_3(d, e, f) {
        // do something
    },
};

# 使用模組
const amanda = require(./amanda.js);
amanda.fanc_1(1, 2);
amanda.fanc_2(3);

另一種匯出物件的簡化語法, 使用特殊變數 exports, 一樣是匯出物件, 包含三個函式

// amanda.js
exports.fanc_1 = function(a, b) {
    // do something
};

exports.fanc_2 = function(c) {
    // do something
};

exports.fanc_3 = function(d, e, f) {
    // do something
};

# 使用模組
const amanda = require(./amanda.js);
amanda.fanc_1(1, 2);
amanda.fanc_2(3);

results matching ""

    No results matching ""