[Express] app.configure と app.use の使い方について

Express では app.configure を使うことで、NODE_ENV の本番環境 (production) 、開発環境 (development) の指定に応じて処理を分岐して設定を行うことができます。今回は具体例として、ミドルウエアを淡々と app.use(fn) で追加していく場合を考えます。

この時 app.use() が呼ばれる順番の通りに app の内部状態が設定されるので、production, development の両方に共通したミドルウエアを末尾の方に追加するには、適切なタイミングまで待ってから fn が呼ばれる app.configure(fn) を使う必要があります。app.configure も呼ばれた順番を尊重してコールバック関数を呼ぶことに要注意です。

また他にも、複数の場合に対応する app.configure(env1, env2, ..., fn) もOKです。NODE_ENV が存在しなかった場合のデフォルト値は development です (express/lib/http.js)。

var express = require('express'),
    app = express();

app.use(function (req, res, next) {
    console.log('1. before config');
    next();
});

app.configure('development', function () {
    app.use(function (req, res, next) {
        console.log('2. development');
        next();
    });
});

app.configure('production', function () {
    app.use(function (req, res, next) {
        console.log('2. production');
        next();
    });
});

app.configure('development', 'production', function () {
    app.use(function (req, res, next) {
        console.log('3. development/production');
        next();
    });
});

app.configure(function () {
    app.use(function (req, res, next) {
        console.log('4. after config');
        next();
    });
});

app.get('/', function (req, res, next) {
    console.log('5. get root');

    res.type('txt');
    res.send('ok');
});

app.listen(3000);

/* 実行例: http://localhost:3000/ をGETした場合

$ node server.js
1. before config
2. development
3. development/production
4. after config
5. get root

$ env NODE_ENV=production node server.js
1. before config
2. production
3. development/production
4. after config
5. get root

*/

2012/12/11 追記
app.configure は v3.0.0 で非推薦メソッドとなっているようです。今後は if (app.get('env') === 'development') などとして分岐すれば良いとのことです。

コメント

このブログの人気の投稿

[linux] ping は通るのに No route to host と言われる

Chrome でダウンロードしたファイル名の一部がハイフンになる

[windows] Windows 回復環境 (WinRE) を修理する