Last active
April 12, 2020 07:42
-
-
Save vafrcor/004bd46b153fe638cce85728ffc323eb to your computer and use it in GitHub Desktop.
NodeJS Config Loader using configstore module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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