在 Node.js 中创建自定义模块

node.jsjavascriptweb developmentfront end technology

node.js 模块是一种包含某些函数或方法的包,供导入它们的人使用。网络上有一些模块供开发人员使用,例如 fs、fs-extra、crypto、stream 等。您也可以创建自己的包并在代码中使用它。

语法

exports.function_name = function(arg1, arg2, ....argN) {
   // 将您的函数主体放在此处...
};

示例 - 自定义 Node 模块

创建两个名为 – 的文件calc.js 和 index.js 并复制以下代码片段。

calc.js 是自定义节点模块,它将保存节点函数。

index.js 将导入 calc.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; // 除以数字
};

index.js

// 使用以下语句导入自定义节点模块
var calculator = require('./calc');

var a = 21 , b = 67

console.log("Addition of " + a + " and " + b + " is " + calculator.add(a, b));

console.log("Subtraction of " + a + " and " + b + " is " + calculator.sub(a, b));

console.log("Multiplication of " + a + " and " + b + " is " + calculator.mul(a, b));

console.log("Division of " + a + " and " + b + " is " + calculator.div(a, b));

输出

C:\home
ode>> node index.js Addition of 21 and 67 is 88 Subtraction of 21 and 67 is -46 Multiplication of 21 and 67 is 1407 Division of 21 and 67 is 0.31343283582089554

相关文章