Node.js でカスタム モジュールを作成する

PHPz
リリース: 2023-09-18 12:17:09
転載
1105 人が閲覧しました

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

node.js モジュールは、インポートする人が使用する特定の関数またはメソッドが含まれるパッケージです。 fs、fs-extra、crypto、stream など、開発者が使用できるモジュールが Web 上にいくつかあります。独自のパッケージを作成してコードで使用することもできます。

構文

exports.function_name = function(arg1, arg2, ....argN) {
   // Put your function body here...
};
ログイン後にコピー

例 - カスタム ノード モジュール

calc.js およびindex.js という名前の 2 つのファイルを作成し、次のコード スニペットをコピーします。

calc.js は、カスタム ノードがノード機能を保持するモジュールです。

index.js は calc.js をインポートし、ノード プロセスで使用します。

calc.js< /p>

//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:\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
ログイン後にコピー

以上がNode.js でカスタム モジュールを作成するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!