Reputation: 6531
Is there a way to make an app with nodejs that can be started with additional parameters? A few examples:
node myApp.js -nolog
would start the app with the custom noLog=true
parameter, so that things would not be console.logged..
node myApp.js -prod
would start the app in a specific set of production settings.
I am not sure if there is anything equivalent in node already.. If this is a duplicate, possibly because I was not even aware of the keyword to search this specific problem's answers.
Enlighten me!
Upvotes: 0
Views: 100
Reputation:
To read command line arguments you need to parse process.argv
, or use a 3rd-party module like minimist:
var argv = require('minimist')(process.argv.slice(2));
// do something ...
var config = argv.config;
if (config === 'dev') {
// set the flag
}
Then start your app via node app.js --config=dev
.
In most general case you need to include more than one option, and manually hardcoding them in code is a bad idea. A recommended way is to write them down in a configutaion file, then use require
to parse. You can use both .js
and .json
to store configutation, but .js
is more convenient because JSON format is too strict, especially it does not even allow you put comments.
So here's a solution. Organize you configurations as follow:
config
├── dev.js
├── production.js
production.js
is defined as a "base class", which stores all required settings, and exposes them using module.export
.
module.exports = {
db: {
backend: 'mysql',
user: 'username',
password: 's3cr3t'
// ...
}
};
dev.js
inherits all properties from production, override the value to fit your local env. It's recommend to ignore this file in version control system (git, SVN, etc.), so your local configutaion will not conflict with others in the project. To deep copy and merge an object, node.extend may help.
var base = require('./production'),
extend = require('node.extend');
var overrides = {
db: {
user: 'root',
password: ''
}
};
module.exports = extend(overrides, base);
Upvotes: 1