苏幕遮零

好好学习,天天向上!

导航

Node.js 定义和引用模块

定义一个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

 

posted on 2017-09-02 09:18  苏幕遮零  阅读(262)  评论(0编辑  收藏  举报