Alex Liang

NodeJS - 初探Module (2)

上一篇介紹module.export的使用方式,這一篇介紹它的底層和其它用法

引入整個資料夾

我們可以將一個module拆成數個js檔案,利用一個index.js便可將整個資料夾打包給其它檔案使用

payment/index.js
1
2
3
4
5
6
7
8
var creditCard = require('credit_card');
var atmTransfer = require('atm');

module.export = {
creditCard: creditCard,
atmTransfer: atmTransfer
};

payment/credit_card.js
1
2
3
4
5
var payment = function(price) {
console.log('Pay $' + price + 'by credit card");
}

module.export = payment;
payment/atm.js
1
2
3
4
5
var payment = function(price) {
console.log('Pay $' + price + 'by ATM transfer");
}

module.export = payment;
app.js
1
2
3
4
var payment = require('./payment');

payment.creditCard();
payment.atmTransfer();

上例將payment底下二種不同的付款方式包在index.js檔案給外部使用

利用json檔將設定包裝起來

currency.json
1
2
3
4
{
"tw": "NTD",
"us": "USD"
}
payment/credit_card.js
1
2
3
4
5
6
7
var currency = require('./currency.json');

var payment = function(price) {
console.log('Pay $' + price + ' ' + currency.us + 'by credit card");
}

module.export = payment;

用這個方式可將設定值包裝成json檔,增加source code的可讀性

原生module

NodeJS內建許多原生module,這裡是api ducuments。我們以util為例

app.js
1
2
3
4
5
var util = require('util');

var price = 100;
var statement = util.format('The price is %s', price);
util.log(statement);
1
$ 28 Nov 14:54:32 - The price is 100

原生module己提供一些方便的功能,遇到問題時上官網查文件說不定己有解決方案