13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nodejsのplugin方式のやり方

Last updated at Posted at 2015-01-29

はじめに

node.jsでモジュールの追加変更を本体のプログラム変更なしに行うやり方です
プラグイン的に追加できるようにしておくと本体のコードをいじらなくて済むのでフレームワークを作るときに
コードの変更なく機能を追加できるので便利です

やりかた

ディレクトリ構造

web/
 app.js
 plugin_loader.js
 /plugins
  /hello
   index.js

プラグインローダー

名前とインスタンス生成のペアを作ります

plugin_loader.js
var fs = require('fs');
var scan = exports.scan = function(dir){
    var files = fs.readdirSync(dir);
    return files.filter(function(v){return fs.statSync([dir, v].join('/')).isDirectory()}).
        map(function(v){
            return {
                name : v,
                createInstance : require([dir, v].join('/')),
            }
        })
}

本体

プラグインの配列ができるのでこれを本体側で呼び出せる仕組みを作ります。
※WEBなどであればURLにページ名を入れておきページ名をプラグイン名にして呼び出すなど。

app.js
var pluginLoader = require('./plugin_loader');
var plugins = pluginLoader.scan(__dirname+'/plugins').reduce(function(r,v){
    r['/'+v.name] = v.createInstance;
    return r;
}, {});

var http = require('http');
var url = require('url');
http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    var urlinfo = url.parse( request.url , true );
    var f = plugins[urlinfo.pathname];
    if(f){
        f(request, response);
    }else{
        response.end();
    }
}).listen(8080);

プラグイン

plugins/hello/index.js
module.exports = function(request, response){
    response.write('hello world');
    response.end();
}

実行

node app.js

起動したらブラウザでテストします

hello world

その他

サンプルはWEBサーバーですが私はボットのエージェントにこの仕組を使ってます。
今のところ問題は出てませんが問題があるとご指摘あればコメントにお願いしたいです。

13
13
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
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?