Skip to content

Instantly share code, notes, and snippets.

@vafrcor
Last active April 12, 2020 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vafrcor/004bd46b153fe638cce85728ffc323eb to your computer and use it in GitHub Desktop.
Save vafrcor/004bd46b153fe638cce85728ffc323eb to your computer and use it in GitHub Desktop.
NodeJS Config Loader using configstore module
const dotenv = require('dotenv');
dotenv.config();
const fs = require('fs');
const approot = require('app-root-path');
const _ = require('lodash');
const ConfigStore = require('configstore');
const app_name = process.env.APP_NAME || 'app_config';
const config_path = process.env.APP_CONFIG_PATH || approot + '/config';
const readdir_mode = process.env.APP_CONFIG_READDIR_MODE || 'recursive';
var readConfigs = function(mode = 'simple', path) {
// mode: simple|recursive
var values={};
fs.readdirSync(path, {withFileTypes: true})
.filter(file => {
return (file.isFile() && (file.name.indexOf('.') !== 0) && (!_.includes(['index.html', 'index.js'], file.name)) && (file.name.slice(-3) === '.js')) || (file.isDirectory());
})
.forEach(file => {
if(mode == 'recursive'){
if(file.isDirectory()){
values[file.name]= readConfigs(mode, path + '/' + file.name);
}else{
values[file.name.replace('.js', '')] = require(path + '/' + file.name);
}
}else{
// simple
values[file.name.replace('.js', '')] = require(path + '/' + file.name);
}
});
return values;
};
var config_values= readConfigs(readdir_mode, config_path);
const config = new ConfigStore(app_name, config_values);
config.clear();
config.all= config_values;
module.exports = config;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment