Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การสร้างโมดูลแบบกำหนดเอง (Custom Modules) ใน Node.js

โมดูลใน Node.js คือแพ็กเกจที่รวมฟังก์ชันหรือเมธอดไว้ เพื่อให้นำเข้าไปใช้งานได้ มีโมดูลในตัวมากมาย เช่น fs, crypto, stream ฯลฯ นอกจากนี้เรายังสามารถสร้างโมดูลของตัวเองได้

ไวยากรณ์

exports.function_name = function(arg1, arg2, ...argN) {
  // ฟังก์ชัน body
};

ตัวอย่าง: โมดูลคำนวณ (Calculator)

สร้าง 2 ไฟล์: 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;
};

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));

ผลลัพธ์

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

โมดูลที่สร้างเองช่วยให้นำโค้ดที่ใช้ซ้ำไปใช้ได้ง่าย และจัดระเบียบโค้ดเป็นระบบ