When building modern applications, especially in multi-environment setups like development, QA, and production, managing environment-specific configurations efficiently is crucial. Manually switching environment settings can be error-prone and time-consuming. This guide demonstrates how to automate the process using Node.js and a simple script.
Problem Statement
In a project with multiple environments, we often have separate configuration files for each environment. Instead of manually renaming or replacing these files when switching environments, we can automate this process with a script.
For example, if we have three environments: dev
, qa
, and prod
, we can use a script to dynamically copy the corresponding configuration file to a unified env.json
file.
Prerequisites
-
Node.js
installed on your system. - Basic knowledge of Node.js file system
(fs)
and path modules.
Folder Structure
Ensure your environment configuration files are organized as follows:
project-root/
│
├── src/
│ ├── config/
│ └── scripts/
│ └── set-environment.js
│ └── envs/
│ ├── dev.json
│ ├── qa.json
│ ├── prod.json
│ └── env.json
-
dev.json
,qa.json
,prod.json
: Contain environment-specific configurations. -
env.json:
The active environment configuration file (automatically generated). -
set-environment.js:
The script to automate the environment setup.
Environment Configuration Files
env.json
This file will be dynamically generated by the script. Here's the format:
{
"API_URL": "",
"ENVIRONMENT": ""
}
prod.json
For production:
{
"API_URL": "https://prod.example.com",
"ENVIRONMENT": "production"
}
dev.json
For production:
{
"API_URL": "https://dev.example.com",
"ENVIRONMENT": "development"
}
qa.json
For QA:
{
"API_URL": "https://qa.example.com",
"ENVIRONMENT": "qa"
}
The Automation Script
Below is the set-environment.js
script:
const fs = require('fs');
const path = require('path');
// Map environment names to JSON files
const envMapping = {
dev: 'dev.json',
qa: 'qa.json',
prod: 'prod.json',
};
// Get the environment argument
const environment = process.argv[2];
console.log("🚀 ~ environment:", environment);
if (!environment || !envMapping[environment]) {
console.error(`Invalid or missing environment argument. Use one of: ${Object.keys(envMapping).join(', ')}`);
process.exit(1);
}
// Resolve paths for source and destination files
const sourceFile = path.resolve(__dirname, `../envs/${envMapping[environment]}`);
const destinationFile = path.resolve(__dirname, '../envs/env.json');
// Check if the source file exists
if (!fs.existsSync(sourceFile)) {
console.error(`Environment file not found: ${sourceFile}`);
process.exit(1);
}
// Copy the selected file to `env.json`
fs.copyFileSync(sourceFile, destinationFile);
console.log("🚀 ~ Environment set to:", environment);
Adding NPM Scripts
To simplify the usage of the script, add the following commands to the scripts
section of your package.json:
"scripts": {
"env:dev": "node ./src/config/scripts/set-environment.js dev",
"env:qa": "node ./src/config/scripts/set-environment.js qa",
"env:prod": "node ./src/config/scripts/set-environment.js prod"
}
How It Works
Environment Mapping: The script uses an envMapping object to map environment names (dev, qa, prod) to their corresponding JSON files (dev.json, qa.json, prod.json).
Command-Line Argument: The desired environment (e.g., dev) is passed as a command-line argument.
File Path Resolution: Using the path module, the script dynamically identifies the source file (dev.json) and the destination file (env.json).
File Existence Check: Before copying, the script ensures that the source file exists, avoiding runtime errors.
File Copy Operation: The fs.copyFileSync method copies the selected configuration file to env.json.
Using the Script
Run the following commands to set the environment:
- For Development:
npm run env:dev
- For QA:
npm run env:qa
- For Production:
npm run env:prod
Benefits
- Automation: Eliminates manual file management.
- Error Prevention: Reduces the risk of incorrect configurations.
- Flexibility: Easily extendable for additional environments.
Conclusion
Automating environment configuration is a simple yet powerful way to improve workflow efficiency in your project. With this setup, you can seamlessly switch between environments with just a single command.
Happy coding! 🚀
Top comments (0)