In the software world - thanks to people who create and maintain open source libraries - there aren't many problems that aren't already solved.
In my quest to manage required environment variables for my Node.js applications, I stumbled upon envalid - a neat utility to ensure that all necessary variables are set before bootstrapping the application.
Manual validation
const cachePath = process.env.CACHE_PATH;
if(typeof cachePath === 'string') {
// Perform other validations
} else {
console.error('Missing CACHE_PATH environment variable.');
process.exit(1);
}
// Repeat for more variables
With envalid
const {cleanEnv, str} = require('envalid');
// Verify required environment variables
const env = cleanEnv(process.env, {
CACHE_PATH: str(),
});
Custom validators
Further, envalid
supports custom validators to add additional checks.
const { makeValidator } = require('envalid');
const fs = require('fs');
const path = require('path');
const {cleanEnv, str} = require('envalid');
const exists = makeValidator(x => {
// Correct path according to current platform
const normalized = path.normalize(x);
if (fs.existsSync(normalized)) {
return normalized;
} else {
throw new Error('Directory does not exist.');
}
}, 'exists');
const env = cleanEnv(process.env, {
CACHE_PATH: exists(),
});
console.log(env.CACHE_PATH);
Further
If you require custom error reporting, you can read more about it.