Heim  >  Artikel  >  Web-Frontend  >  Erstellen Sie benutzerdefinierte Module in Node.js

Erstellen Sie benutzerdefinierte Module in Node.js

PHPz
PHPznach vorne
2023-09-18 12:17:091179Durchsuche

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

Ein node.js-Modul ist ein Paket, das bestimmte Funktionen oder Methoden zur Verwendung durch diejenigen enthält, die sie importieren. Im Web stehen Entwicklern mehrere Module zur Verfügung, z. B. fs, fs-extra, crypto, stream usw. Sie können auch Ihr eigenes Paket erstellen und es in Ihrem Code verwenden.

Syntax

exports.function_name = function(arg1, arg2, ....argN) {
   // Put your function body here...
};

Beispiel – Benutzerdefiniertes Knotenmodul

Erstellen Sie zwei Dateien mit den Namen calc.js und index.js und kopieren Sie die folgenden Codeausschnitte.

calc.js ist das Modul, in dem der benutzerdefinierte Knoten die Funktionalität des Knotens enthält.

index.js importiert calc.js und verwendet es im Knotenprozess.

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

output

C:\homeode>> 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

Das obige ist der detaillierte Inhalt vonErstellen Sie benutzerdefinierte Module in Node.js. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:tutorialspoint.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen