LoginSignup
16
25

More than 5 years have passed since last update.

nodeモジュールを作成する

Last updated at Posted at 2018-07-20

言語は異なっても、プログラムの組み方はなかなか変えられないもの。
自分のパターンのメソッド名でラップして自分のライブラリに置いておきたい。
nodeでクラス化して置いておきたい場合はどうする?
ということで、nodeモジュールの作成方法のメモ。

環境

Node.js v6.11.0

参考

Node.js v6.11.0 Documentation

仕様

Node.jsでは、ファイルとモジュールは1対1で対応しています(各ファイルは個別のモジュールとして扱われます)。

たとえば、foo.jsという名前のファイルを考えてみましょう。

foo.js
const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);

最初の行で、foo.jsは、foo.jsと同じディレクトリにあるcircle.jsモジュールをロードします。
circle.jsの内容は次のとおりです。

circle.js
const { PI } = Math;
exports.area = (r) => PI * r * r;
exports.circumference = (r) => 2 * PI * r;

モジュールcircle.jsは、関数area()とcircumference()をexportsしています。
関数とオブジェクトを追加するには、それらをexportsオブジェクトに追加します。

モジュールがNode.jsによって関数にラップされるため、モジュールのローカル変数はプライベートになります。 この例では、変数PIはcircle.jsに対してプライベートです。

モジュールのエクスポートのルートを関数(コンストラクタなど)にする場合や、一度に1つのプロパティを作成するのではなく、1つの割り当てで完全なオブジェクトをエクスポートする場合は、エクスポートの代わりにmodule.exportsに割り当てます 。

以下、bar.jsはコンストラクタをエクスポートするsquareモジュールを使用します。

bar.js
const square = require('./square.js');
const mySquare = square(2);
console.log(`The area of my square is ${mySquare.area()}`);

squareモジュールはsquare.jsで定義されています。

square.js
// assigning to exports will not modify module, must use module.exports
module.exports = (width) => {
  return {
    area: () => width * width
  };
};

モジュールシステムはrequire( 'module')モジュールに実装されています。

実践

例えば、Slack APIを操作するためのラップされたクラスを用意したいとします。
私のクラス名命名規則は接頭辞にHKを付けているので、クラス名をHKSlackとします。
また、ファイル名とクラス名を一致させてるので、以下の様なファイルになります。
Slack Web API

HKSlack.js
/**
 * constructor
 *
 * @return void
 */
var HKSlack = function(token)
{
    this.token = token;
}
/**
 * Set Token
 *
 * @param string $token
 * @return void
 */
HKSlack.prototype.setToken = function(token)
{
    this.token = token;
}
/**
 * Get Token
 *
 * @return string
 */
HKSlack.prototype.getToken = function()
{
    return this.token;
}
/**
 * Post Chat Message
 *
 * @param
 * @return void
 */
HKSlack.prototype.postMessage = function(json)
{
    var Slack = require('slack-node'); // slack-node モジュールを読み込んでいる
    var slack = new Slack(this.getToken());
    slack.api('chat.postMessage', json, function(err, response) {
        console.log(response);
    });
}
module.exports = HKSlack;

最後に、作成したクラスをmodule.exportsに割り当てています。
このモジュールを利用する場合、以下の様になります。

post_slack.js
var token = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var HKSlack = require('./HKSlack.js');
var slack = new HKSlack(token);
slack.postMessage({
    'channel': '#mychannel',
    'username': username,
    'text': text
});

今回はここまで。

16
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
25