Introduction to Check-Env
Check-Env is a powerful Node.js library designed to automate and streamline the process of validating environment variables. For developers, managing environment configurations effectively is essential for building secure and scalable applications. With Check-Env, it becomes simpler to handle these configurations, ensuring that variables are set correctly and reducing runtime errors.
Common Check-Env APIs with Examples
init()
Initializes the checks that will be performed. This method must be called before other API methods.
const checkEnv = require('check-env');
checkEnv.init();
check()
Verifies that the specified environment variable is set and optionally validates its value.
checkEnv.check('DB_HOST'); // Ensures DB_HOST is set
checkEnv.check('NODE_ENV', ['development', 'production']); // Ensures NODE_ENV is either 'development' or 'production'
checkAll()
Verifies that all specified environment variables are set and optionally validates their values.
checkEnv.checkAll({
'DB_HOST': undefined,
'PORT': undefined,
'NODE_ENV': ['development', 'production']
});
hasErrors()
Returns a boolean indicating whether there are any errors in the configured checks.
if (checkEnv.hasErrors()) {
console.error("Environment configuration errors detected!");
}
getErrors()
Returns an array of error messages indicating what checks failed.
const errors = checkEnv.getErrors();
if (errors.length) {
errors.forEach(error => console.error(error));
}
Example: Setting Up an Application with Check-Env
Below is a simple example of how to set up a Node.js application to use Check-Env to manage its environment variables:
// app.js
const express = require('express');
const checkEnv = require('check-env');
// Initialize Check-Env
checkEnv.init();
// Define required and optional environment variables
checkEnv.checkAll({
'DB_HOST': undefined,
'DB_USER': undefined,
'DB_PASS': undefined,
'PORT': '3000',
'NODE_ENV': ['development', 'production']
});
// Check for environment configuration errors
if (checkEnv.hasErrors()) {
console.error('Environment configuration errors:');
checkEnv.getErrors().forEach(error => console.error(error));
process.exit(1);
}
// If no errors, proceed to set up the app
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`App running on port ${port}`);
});
This setup ensures that your application checks for the necessary environment variables before starting, preventing potential runtime errors due to missing or misconfigured variables.
Start using Check-Env today to maintain error-free environment configurations and build robust applications.
Hash: 9de9289fb5cdab496d7aefcb22c326bb61b71713e251e0d6ec5858dd6447f738