I’m trying to develop a class with static methods on a NodeJs application, as a Config module purpose.
I would like to access to it from different modules without instantiate every time a new object.
1) Is it correct to use an approach like below, avoiding the class prototype?
function Config(){
}
Config.svrPort=function(){
return 8080;
}
Config.dbName=function(){
return "myDbName";
}
module.exports = Config;
2) Are there any other solutions?
3) Is it also a valid approach to put different objects in the same module (e.g. config.js) like this?
exports.server=function(){
return{
port:8080
};
};
exports.database=function(){
return{
name:"myDbName",
user:"root",
password:"myPassword",
host:"localhost",
port:3306
};
};
and finally to use it as:
var config = require('./config');
config.server().port
config.database().name
That is the correct approach although in your example you could simply store the values as primitives: Config.SVR_PORT = 8080
, note I rewrote those as "constants", since I don't recommend changing statics.
When this is said, then please note: Do not put any sensitive data (passwords, etc) in your JavaScript files, but instead put these in a config file. This will separate config from code. And help you not to leak any potential critical information.
db-secrets.json
{
"password": "...",
...
}
Then you can access the secrets by making a wrapper module:
// Wrapper module for db-secrets.json
var fs = require('fs');
exports = JSON.parse(fs.readFileSync('db-secrets.json'), 'utf8');
Or make a db connect module db-connect.js
:
var fs = require('fs');
var db = require('db');
var db_secrets = JSON.parse(fs.readFileSync('db-secrets.json'), 'utf8');
export = function() {
return db.connect(db_secrets.user, db_secrets.password, ...);
};
If you use git for source control you can easily add the following to your .gitignore
which will make sure your sensitive file is not added to git:
.gitignore
db-secrets.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With