Quite recently I was talking about NodeJS and the way it works to a bunch of developers. I was not impressed by the way they were handling application initialization states. Especially how they treated their production vs development environments and username and password. This is not the first case I have seen people spray their user names across application. I explained to them the need for keeping it clean. As much as I told them that, thought a short post will help everybody.
I prefer to use singleton for this case. These seldom change during development. With that said, I'd like to keep it very short. We have a simple app.js, that prints hello world. It will need to know if the application is running in DEV or PRODUCTION mode.
Here's the structure, I chose to go with
app.js
env.json
environment/index.js
environment/locateEnv.js
Run app.js through node or nodemon. env information is available. No matter how many JS files you create in the application, you can now import/require environment in them and get information in a nicer way.
I prefer to use singleton for this case. These seldom change during development. With that said, I'd like to keep it very short. We have a simple app.js, that prints hello world. It will need to know if the application is running in DEV or PRODUCTION mode.
Here's the structure, I chose to go with
app.js
var environment = require('./environment')
console.log('Hello World!!!');
console.log(environment.environmentJSON());
env.json
{
"development": {
"aws_user_id": "facebook_dummy_dev_app_id",
"aws_user_passwd": "facebook_dummy_dev_app_secret"
},
"production": {
"aws_user_id": "facebook_dummy_prod_app_id",
"aws_user_passwd": "facebook_dummy_prod_app_secret"
}
}
environment/index.js
module.exports = require('./locateEnvFile');
environment/locateEnv.js
var env = require('./../env');
module.exports.environmentJSON = function locateEnvironmentJSONFile() {
var node_env = process.env.NODE_ENV || 'development';
return env[node_env];
};
Run app.js through node or nodemon. env information is available. No matter how many JS files you create in the application, you can now import/require environment in them and get information in a nicer way.

No comments:
Post a Comment