Node.js モジュールを作成する方法

ADVERTISEMENT

はじめに
このクイックチュートリアルで、あなた独自の Node.js モジュールを作成する方法について学びます。
すべての設定とデプロイを行ったら、アプリケーションのライフサイクルの重要な部分である、アプリケーションを監視するオプションを調べたいと思うかもしれません。
Node.js をダウンロードおよびインストールするには、以下のリストから OS を選択します。
Create a Node project
以下のコマンドを使用して空のプロジェクトを作成します:
mkdir MyCoolModule
以下のコマンドを実行します:
cd MyCoolModulenpm init
必須フィールド(名前とバージョン)と、メインフィールドの応答を提供します:
名前:あなたのモジュール名.バージョン.バージョン.名前: あなたのモジュール名: 初期モジュールのバージョン。 セマンティックバージョニングガイドラインに従い、1.0.0.main から始めることをお勧めします。 main: モジュールが他のアプリケーションによって必要とされるときにロードされるファイルの名前。 デフォルトの名前は index.js です。
Just press ‘Enter’ to the other questions…
Write your module
There should now be a package.json
file inside your project directory.
注意: この例では、コンソールにテキストを表示する関数を書いています。
プロジェクト ディレクトリにファイルを作成し、名前を index.js
にします。 次のコードをコピーして index.js に貼り付けます:
exports.printMsg = function() { console.log("Node.js is awesome!");}
Publish the module to NPM (Node Package Manager)
npmアカウントをお持ちでない場合 – 下記から作成してください:
認証情報を使用してログイン:
npm login
ログインしたら、発行する準備ができました!
NPMアカウントにログインしていることを確認してください:
npm publish

Test your module
Create another directory:
mkdir TestMyModule
Switch into the directory:
cd TestMyModule
Create your test script – I called test.js
.このディレクトリに、テスト スクリプトを作成することができます。
var mymodule = require('mycoolmodule')mymodule.printMsg();
テストノードプロジェクトの作成:
npm init
作成したモジュールをインストール:
npm install mycoolmodule
テストスクリプトの実行:
node test.js
