Skip to content

Instantly share code, notes, and snippets.

@syamn
Last active December 23, 2015 23:19
Show Gist options
  • Save syamn/6708755 to your computer and use it in GitHub Desktop.
Save syamn/6708755 to your computer and use it in GitHub Desktop.
console.log('called another.js');
console.log(require.main.exports.config('APP_PORT'));
// Load Configuration
var config = module.exports.config = require('./config.js');
console.log(config('APP_PORT'));
require('./another.js');
return;
/* Application configuration file */
//exports.APP_PORT = '8000'; // 直接exportsだと外部から変更されるかも
//var APP_PORT = '8000'; // これだと値を取るのにeval使うことに
var config = Array;
config['PORT'] = '8000';
module.exports = function get(name){
//return eval(name);
return config[name];
}
@syamn
Copy link
Author

syamn commented Sep 26, 2013

Nodeで設定ファイルを持ち回る良い方法が良く分からなかったので自分の中の最終形?

config.jsで値を直接exportsして持ち歩くと外部から自由に設定できてしまうので、
getterのみをmodule.exportsして、外部から利用したい設定変数名を引数にconfig.jsをコールする。

app.jsの2行目でmodule.exports.configに入れておいて、別のモジュールからはrequire.main.exports.configでアクセスする。

config.jsで与えられた変数名をevalするのが気に入らないんだけど、他に上手いこと動的に変数名を変えて値を取れる方法あれば教えて!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment