建立 hello-world.js 模組

Node 提供 module.exports 介面,以將函式和變數公開給其他檔案。最簡單的方法是隻匯出一個物件(函式或變數),如第一個示例所示。

你好,world.js

module.exports = function(subject) {
    console.log('Hello ' + subject);
};

如果我們不希望整個匯出成為單個物件,我們可以將函式和變數匯出為 exports 物件的屬性。以下三個示例都以略微不同的方式展示了這一點:

  • hello-venus.js:函式定義單獨完成,然後作為 module.exports 的屬性新增
  • hello-jupiter.js:函式定義直接作為 module.exports 的屬性值
  • hello-mars.js:函式定義直接宣告為 exports 的屬性,exportsmodule.exports 的簡短版本

你好,venus.js

function hello(subject) {
    console.log('Venus says Hello ' + subject);
}

module.exports = {
    hello: hello
};

你好,jupiter.js

module.exports = {
    hello: function(subject) {
      console.log('Jupiter says hello ' + subject);
    },

    bye: function(subject) {
      console.log('Jupiter says goodbye ' + subject);
    }
};

你好,mars.js

exports.hello = function(subject) {
    console.log('Mars says Hello ' + subject);
};

載入具有目錄名稱的模組

我們有一個名為 hello 的目錄,其中包含以下檔案:

index.js

// hello/index.js
module.exports = function(){
    console.log('Hej');
};

main.js

// hello/main.js
// We can include the other files we've defined by using the `require()` method
var hw = require('./hello-world.js'),
    hm = require('./hello-mars.js'),
    hv = require('./hello-venus.js'),
    hj = require('./hello-jupiter.js'),
    hu = require('./index.js');

// Because we assigned our function to the entire `module.exports` object, we
// can use it directly
hw('World!'); // outputs "Hello World!"

// In this case, we assigned our function to the `hello` property of exports, so we must
// use that here too
hm.hello('Solar System!'); // outputs "Mars says Hello Solar System!"

// The result of assigning module.exports at once is the same as in hello-world.js
hv.hello('Milky Way!'); // outputs "Venus says Hello Milky Way!"

hj.hello('Universe!'); //  outputs "Jupiter says hello Universe!"
hj.bye('Universe!'); // outputs "Jupiter says goodbye Universe!"

hu(); //output 'hej'