在 Node.js 中创建自定义模块
该node.js模块是一种包,它包含某些功能或方法,那些谁进口他们使用。Web上提供了一些模块供开发人员使用,例如fs、fs-extra、crypto、stream等。您也可以制作自己的包并在代码中使用它。
语法
exports.function_name = function(arg1, arg2, ....argN) {
//把你的函数体放在这里...
};示例-自定义节点模块
创建两个文件,名字-calc.js和index.js并复制下面的代码片段。
这calc.js是将保存节点功能的自定义节点模块。
在index.js将导入calc.js并在节点过程中使用。
计算器
//创建自定义节点模块
//并制作不同的功能
exports.add = function (a, b) {
return a + b; //添加数字
};
exports.sub = function (a, b) {
return a - b; //减去数字
};
exports.mul = function (a, b) {
return a * b; //乘以数字
};
exports.div = function (a, b) {
return a / b; //划分数字
};索引.js
//使用以下语句导入自定义节点模块
var calculator = require('./calc');
var a = 21 , b = 67
console.log("外加的 " + a + " and " + b + " is " + calculator.add(a, b));
console.log("减去 " + a + " and " + b + " is " + calculator.sub(a, b));
console.log("乘法 " + a + " and " + b + " is " + calculator.mul(a, b));
console.log("分工 " + a + " and " + b + " is " + calculator.div(a, b));输出结果C:\home\node>> node index.js 外加的 21 and 67 is 88 减去 21 and 67 is -46 乘法 21 and 67 is 1407 分工 21 and 67 is 0.31343283582089554
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志