Introduction to adjust-env
The adjust-env package is a powerful tool that allows developers to dynamically adjust environment variables for application development and testing. It provides a range of APIs that make managing environment-specific configurations straightforward and efficient.
Basic Usage
The following example demonstrates how to set and get environment variables using adjust-env:
const { setEnv, getEnv } = require('adjust-env');
// Set an environment variable
setEnv('MY_ENV_VAR', 'some value');
// Get an environment variable
const myEnvVar = getEnv('MY_ENV_VAR');
console.log(myEnvVar); // Outputs: some value
Conditional Environment Settings
You can also set environment variables conditionally:
const { setEnv } = require('adjust-env');
if (process.env.NODE_ENV === 'development') {
setEnv('DEBUG', 'true');
}
Loading Environment Variables from a File
adjust-env supports loading variables from a .env file:
const { loadEnvFromFile } = require('adjust-env');
// Load variables from .env file
const envVars = loadEnvFromFile('.env');
console.log(envVars); // Outputs all env variables loaded from file
App Example
Here is a simple application that demonstrates the use of adjust-env:
const express = require('express');
const { setEnv, getEnv, loadEnvFromFile } = require('adjust-env');
// Load environment variables
loadEnvFromFile('.env');
// Create an Express app
const app = express();
// Example middleware to adjust environment
app.use((req, res, next) => {
if (req.query.env === 'production') {
setEnv('NODE_ENV', 'production');
} else {
setEnv('NODE_ENV', 'development');
}
next();
});
app.get('/', (req, res) => {
res.send(`Running in ${getEnv('NODE_ENV')} mode`);
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
adjust-env is highly flexible and can significantly streamline the configuration management process in your applications.
Hash: 1807c2ebfd08ae44dc769bffcc4d911a8911975a59044cfef3a8cb541497560c