Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jagretz opened this issue Oct 21, 2020 · 1 comment

Comments

@jagretz
Copy link

jagretz commented Oct 21, 2020

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 jagretz changed the title Question: Is there a setting to allow fallback (default?) configuration if a Question: Is there a setting to allow fallback (default?) configuration if a config file does not exist? Oct 21, 2020
@fabhed
Copy link

fabhed commented Aug 2, 2021

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)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants