定义一个Node模块:currency.js
var canadianDollar = 0.91; function roundTwoDecimals(amount) { return Math.round(amount * 100) / 100; } exports.canadianToUS = function (canadian) { return roundTwoDecimals(canadian * canadianDollar); } exports.USToCanadian = function (us) { return roundTwoDecimals(us / canadianDollar); }
引入一个模块:
下面的test-currency.js中的代码,它require了currency.js模块:
var currency = require('./currency'); console.log('50 Canadian dollars equals this amount of US dollars:'); console.log(currency.canadianToUS(50)); console.log('30 US dollars equals this amount of Canadian dollars:'); console.log(currency.USToCanadian(30));
输出结果:
50 Canadian dollars equals this amount of US dollars: 45.5 30 US dollars equals this amount of Canadian dollars: 32.97