Express.js を使用して小さな Node アプリをserver.js
構築しています。ファイルをできるだけきれいに保つために、外部ファイルで構成を構築したいと考えています。サーバーの外観は次のとおりです。
// server.js
var express = require( 'express' );
var app = express();
app.enable( 'trust proxy' );
// Set application config params
require( './config.js' )( app, express );
// Load routes and start listening...
require( './routes' )( app );
app.listen( app.get( 'port' ) );
私のファイルはいくつかのデフォルトを設定してから、特定の構成関数で構成config.js
を更新または上書きします。NODE_ENV
その厄介なタイミングを除いて、すべてがうまくいくでしょう.
私のルートは、いくつかの設定値にアクセスする必要があります。ルートがロードされ、構成が完全にロードされた後にのみサーバーがリッスンを開始するようにする方法はありますか? より良い方法はありますか?
私はイベント ループを取得しますが、私は node/express の初心者であるため、ほぼすべてのことに対してオープンです。さまざまな記事やドキュメンテーション ソースで読んだ経験に基づいて、自分がやりたいとわかっていることを組み合わせて、これを作り上げているようなものです。あまりにも的外れだとは思いませんが、楽観的すぎるのかもしれません。
アップデート
私のconfig.js
。
module.exports = function( app, express ) {
var config = this;
app.configure( function() {
app.set( 'port', 3000 );
app.set( 'datasources', {
'api' : {...},
'mysql' : {...}
});
app.use( express.logger() );
app.use( express.bodyParser() );
app.use( express.cookieParser() );
app.use( express.methodOverride() );
app.use( app.router );
});
// dev-specific config
app.configure( 'development', function() {
console.log( 'Loading development configuration' );
app.use( express.errorHandler({ dumpExceptions: true, showStack: true }) );
// update the mysql config with a connection object
var datasources = app.get( 'datasources' );
var mysqlConnection = require( 'mysql' ).createConnection({...});
datasources.mysql.connection = mysqlConnection;
app.set( 'datasources', datasources );
});
// stg-specific config
app.configure( 'staging', function() {
console.log( 'Loading staging configuration' );
app.use( express.errorHandler() );
// update the mysql config with a connection object
var datasources = app.get( 'datasources' );
var mysqlConnection = require( 'mysql' ).createConnection({...});
datasources.mysql.connection = mysqlConnection;
app.set( 'datasources', datasources );
});
// prd-specific config
app.configure( 'production', function() {
console.log( 'Loading production configuration' );
app.use( express.errorHandler() );
});
console.log( app.get( 'datasources' ) );
console.log( 'Configuration loaded' );
return config;
};