该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