0.2.0 • Published 5 months ago
dotenv-pro v0.2.0
EnvPro
A powerful and flexible .env file manager for Node.js applications with type conversion, comments support, and structured environment variable management.
Features
- 📝 Parse, read, update, and write
.env
files with ease - 🔄 Automatic type conversion (strings, numbers, booleans, arrays, JSON objects)
- 💬 Support for comments (standalone and inline)
- 🔍 Smart detection of data types
- 🧩 Structured organization of variables with comments
- 🚀 Simple and intuitive API
- 🔒 Preserves file structure and formatting
- 🛠️ Built with TypeScript for type safety
📦 Installation
Using npm:
npm install env-pro
Using yarn:
yarn add env-pro
Using bun:
bun add env-pro
Quick Start
import { Env } from 'env-pro';
// Initialize env-pro (defaults to .env in current directory)
const env = Env();
// Add variables
env.add('PORT', '3000');
env.add('DEBUG', 'true');
env.add('API_URL', 'https://api.example.com');
env.add('ALLOWED_ORIGINS', 'http://localhost:3000,https://example.com');
// Read variables (with automatic type conversion)
const port = env.get('PORT'); // Returns number: 3000
const debug = env.get('DEBUG'); // Returns boolean: true
const origins = env.get('ALLOWED_ORIGINS'); // Returns array: ['http://localhost:3000', 'https://example.com']
// Update variables
env.update('PORT', '8080');
// Check if variable exists
if (env.has('DATABASE_URL')) {
// Do something
}
// Delete variables
env.delete('TEMP_VAR');
// Clear all variables
env.clear();
// Save changes to file (done automatically by default)
env.save();
API Reference
Initialization
// Default options
const env = Env();
// Custom options
const env = Env({
path: './config/.env.production',
autoSave: true,
createIfNotExist: true,
defaults: {
NODE_ENV: 'development',
PORT: '3000'
}
});
Options
Option | Type | Default | Description |
---|---|---|---|
path | string | ./.env | Path to the .env file |
autoSave | boolean | true | Automatically save changes to file |
createIfNotExist | boolean | true | Create the file if it doesn't exist |
autoSync | boolean | false | Auto-sync with process.env |
defaults | object | {} | Default values to set when initializing |
Methods
Basic Operations
add(name, value, comment?)
- Add a new variableget(name)
- Get a variable's value (with type conversion)update(name, value, comment?)
- Update an existing variabledelete(name)
- Delete a variablehas(name)
- Check if a variable existsclear()
- Clear all variables, comments, and empty lines
Comments
addComment(comment)
- Add a standalone commentgetComment(name)
- Get a comment for a variableupdateComment(lineNum, comment)
- Update a commentdeleteComment(lineNum)
- Delete a commentgetAllComments()
- Get all comments
Empty Lines
addEmpty()
- Add an empty linedeleteEmpty(lineNum)
- Delete an empty line
File Operations
save()
- Save changes to fileparse()
- Parse the .env filegetAll()
- Get all items (variables, comments, empty lines)reindex()
- Reindex all items
Input Formats
env-pro supports multiple input formats for adding variables:
// Simple key-value
env.add('PORT', '3000');
// Key-value with comment
env.add('PORT', '3000', 'Server port');
// Array format
env.add(['PORT', '3000']);
env.add(['PORT', '3000', 'Server port']);
// Object format
env.add({ name: 'PORT', value: '3000' });
env.add({ name: 'PORT', value: '3000', comment: 'Server port' });
// Raw line (advanced)
env.add('PORT=3000 # Server port');
Type Conversion
env-pro automatically converts values to appropriate types:
Input | Converted Value |
---|---|
'3000' | 3000 (number) |
'3.14' | 3.14 (number) |
'true' , 'yes' , 'on' | true (boolean) |
'false' , 'no' , 'off' | false (boolean) |
'item1,item2,item3' | ['item1', 'item2', 'item3'] (array) |
'{"key":"value"}' | {key: 'value'} (object) |
'[1,2,3]' | [1, 2, 3] (array) |
Examples
Web Server Configuration
// Load .env file
const env = Env();
// Create a server config
const serverConfig = {
port: env.get('PORT') || 3000,
host: env.get('HOST') || 'localhost',
env: env.get('NODE_ENV') || 'development',
corsOrigin: env.get('CORS_ORIGIN') || '*'
};
// Use in Express.js
const app = express();
app.listen(serverConfig.port, serverConfig.host, () => {
console.log(`Server running at http://${serverConfig.host}:${serverConfig.port}`);
});
Database Configuration
// Load .env file
const env = Env();
// Create database config
const dbConfig = {
host: env.get('DB_HOST'),
port: env.get('DB_PORT'),
user: env.get('DB_USER'),
password: env.get('DB_PASS'),
database: env.get('DB_NAME'),
ssl: env.get('DB_SSL'),
pool: {
min: env.get('DB_POOL_MIN'),
max: env.get('DB_POOL_MAX')
}
};
// Connect to database
const db = createConnection(dbConfig);
Feature Flags
// Load .env file
const env = Env();
// Configure feature flags
const features = {
newUI: env.get('ENABLE_NEW_UI'),
analytics: env.get('ENABLE_ANALYTICS'),
notifications: env.get('ENABLE_NOTIFICATIONS')
};
// Use in application
if (features.newUI) {
app.use(newUIMiddleware());
}
Advanced Usage
Working with Comments
// Add a section comment
env.add('# API Configuration');
// Add variable with inline comment
env.add('API_URL', 'https://api.example.com', 'Production API endpoint');
// Add an empty line for readability
env.addEmpty();
// Add another section
env.add('# Database Configuration');
env.add('DB_HOST', 'localhost');
Structured Configuration
// Define sections
const sections = [
{
title: 'Server Configuration',
variables: [
{ name: 'PORT', value: '3000', comment: 'Server port' },
{ name: 'HOST', value: 'localhost' },
{ name: 'NODE_ENV', value: 'development' }
]
},
{
title: 'Database Configuration',
variables: [
{ name: 'DB_HOST', value: 'localhost' },
{ name: 'DB_PORT', value: '5432' },
{ name: 'DB_USER', value: 'postgres' }
]
}
];
// Clear existing config
env.clear();
// Add sections
sections.forEach(section => {
env.add(`# ${section.title}`);
section.variables.forEach(variable => {
env.add(variable.name, variable.value, variable.comment);
});
env.addEmpty(); // Add empty line between sections
});
🤝 Contriuting
Contributions are welcome! soon.
📝 License
This project is licensed under the MIT License - see the LICENSE file for details.