node-convict icon indicating copy to clipboard operation
node-convict copied to clipboard

Question: Is there a setting to allow fallback (default?) configuration if a config file does not exist?

Open jagretz opened this issue 5 years ago • 1 comments

Hello, I wasn't able to find an answer to this question in other issues, so here it is:

I am wondering if there is a standard or recommended way to have the default configuration for an environment loaded with config.load or config.loadFile if a config file is not found? Using part of the example config.js from the docs to illustrate,

var convict = require('convict');

// Define a schema
var config = convict({
  env: {
    doc: 'The application environment.',
    format: ['production', 'development', 'test'],
    default: 'development',
    env: 'NODE_ENV'
  },
  ip: {
    doc: 'The IP address to bind.',
    format: 'ipaddress',
    default: '127.0.0.1',
    env: 'IP_ADDRESS',
  },
  port: {
    doc: 'The port to bind.',
    format: 'port',
    default: 8080,
    env: 'PORT',
    arg: 'port'
  }
});

// Load environment dependent configuration
var env = config.get('env');
config.loadFile('./config/' + env + '.json');

module.exports = config;

And say you have a development.json, test.json, and production.json. Then you run your configuration with NODE_ENV=local. The script will fail with the error Cannot find module './config/local.json'.

Is there a way to have it use the default env setting development in this situation?

Quick aside. I know I can write my own "check if the file exists" function. I am wondering if there is already something built-in.

Thanks!

jagretz avatar Oct 21 '20 15:10 jagretz

I solved it by simply looking if the config file exists:

const configPath = path.join(__dirname, './config.json')
if (fs.existsSync(configPath)) {
  config.loadFile(configPath)
}

fabhed avatar Aug 02 '21 11:08 fabhed