LoginSignup
0
3

More than 5 years have passed since last update.

Expressのルーティングを動的に追加する

Posted at

今作っているシステムがプラグイン的にMVCをモジュールとしてパッケージングして自由に拡張できるようにしているのですが、特定のディレクトリ以下にある(階層構造可)ファイルを読み込むようにしています。

そこでこんな感じでルーティングを自動追加するようにしました。

var addRouter = (app, path) => {
  fs.readdir(path, (error, files) => {
    for (var i in files) {
      let dir = files[i];
      if (dir.indexOf('.') == 0) {
        continue;
      }
      if (fs.statSync(`${path}/${dir}`).isFile()) {
        continue;
      }
      if (fs.existsSync(`${path}/${dir}/index.js`)) {
        var lib = require(`${path}/${dir}`);
        let url_path = path.replace(`${__dirname}/modules`, "") + `/${dir}`;
        console.log("Add rountes", url_path)
        app.use(`${url_path}`, lib.router);
      }
      addRouter(app, `${path}/${dir}`);
    }
  });
}

addRouter(app, `${__dirname}/modules`);

addRouterを再帰的に実行して、 modules 以下にあるディレクトリに index.js があればそれをモジュールとして読み込みます。例えば users というディレクトリであれば、 /users というルーティングが使われます。 admin/users であっても同様です。全部非同期でやるとネストが深くなりそうだったので、一部Syncにしています…。

0
3
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
0
3