What is convict?
Convict is a configuration management tool for Node.js applications. It allows you to define a schema for your configuration files, validate them, and load them from various sources such as JSON files, environment variables, or command-line arguments.
What are convict's main functionalities?
Define a Configuration Schema
This feature allows you to define a schema for your configuration. The schema can include various types of data such as strings, numbers, and arrays. You can also specify default values and environment variables.
const convict = require('convict');
const config = convict({
env: {
doc: 'The application environment.',
format: ['production', 'development', 'test'],
default: 'development',
env: 'NODE_ENV'
},
port: {
doc: 'The port to bind.',
format: 'port',
default: 8080,
env: 'PORT'
}
});
console.log(config.get('env'));
Load Configuration from Multiple Sources
Convict allows you to load configuration from multiple sources such as JSON files, environment variables, and command-line arguments. This makes it easy to manage configuration in different environments.
const convict = require('convict');
const config = convict({
env: {
doc: 'The application environment.',
format: ['production', 'development', 'test'],
default: 'development',
env: 'NODE_ENV'
},
port: {
doc: 'The port to bind.',
format: 'port',
default: 8080,
env: 'PORT'
}
});
config.loadFile('./config.json');
config.load({ port: 3000 });
console.log(config.get('port'));
Validate Configuration
Convict can validate your configuration against the schema you defined. This ensures that your configuration is correct and helps prevent runtime errors.
const convict = require('convict');
const config = convict({
env: {
doc: 'The application environment.',
format: ['production', 'development', 'test'],
default: 'development',
env: 'NODE_ENV'
},
port: {
doc: 'The port to bind.',
format: 'port',
default: 8080,
env: 'PORT'
}
});
config.validate({ allowed: 'strict' });
console.log('Configuration is valid');
Other packages similar to convict
config
The 'config' package is another popular configuration management tool for Node.js. It allows you to define configuration files for different environments and load them based on the current environment. Unlike Convict, it does not provide schema validation out of the box.
dotenv
The 'dotenv' package is a simple module that loads environment variables from a .env file into process.env. It is more lightweight compared to Convict and does not provide schema validation or support for multiple configuration sources.
nconf
The 'nconf' package is a hierarchical configuration manager for Node.js. It allows you to load configuration from multiple sources and provides a flexible way to manage configuration. However, it does not provide schema validation like Convict.