node.js मॉड्यूल एक प्रकार का पैकेज है जिसमें कुछ फ़ंक्शन या विधियाँ होती हैं जिनका उपयोग उन लोगों द्वारा किया जाता है जो उन्हें आयात करते हैं। कुछ मॉड्यूल वेब पर मौजूद हैं जिनका उपयोग डेवलपर्स द्वारा किया जा सकता है जैसे fs, fs-extra, क्रिप्टो, स्ट्रीम, आदि। आप अपना खुद का एक पैकेज भी बना सकते हैं और इसे अपने कोड में उपयोग कर सकते हैं।
सिंटैक्स
exports.function_name = function(arg1, arg2, ....argN) {
// Put your function body here...
}; उदाहरण - कस्टम नोड मॉड्यूल
नाम के साथ दो फाइल बनाएं - कैल्क.जेएस और इंडेक्स.जेएस और नीचे दिए गए कोड स्निपेट को कॉपी करें।
Calc.js कस्टम नोड मॉड्यूल है जो नोड फ़ंक्शन को बनाए रखेगा।
index.js, calc.js आयात करेगा और इसका उपयोग नोड प्रक्रिया में करेगा।
calc.js
//Creating a custom node module
// And making different functions
exports.add = function (a, b) {
return a + b; // Adding the numbers
};
exports.sub = function (a, b) {
return a - b; // Subtracting the numbers
};
exports.mul = function (a, b) {
return a * b; // Multiplying the numbers
};
exports.div = function (a, b) {
return a / b; // Dividing the numbers
}; index.js
// Importing the custom node module with the below statement
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\node>> 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