🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more →
Sign In

dotenv-pro

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dotenv-pro

🛠️ Parse, read, update, and write `.env` files with ease

latest
npmnpm
Version
0.2.0
Version published
Maintainers
1
Created
Source

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

OptionTypeDefaultDescription
pathstring./.envPath to the .env file
autoSavebooleantrueAutomatically save changes to file
createIfNotExistbooleantrueCreate the file if it doesn't exist
autoSyncbooleanfalseAuto-sync with process.env
defaultsobject{}Default values to set when initializing

Methods

Basic Operations

  • add(name, value, comment?) - Add a new variable
  • get(name) - Get a variable's value (with type conversion)
  • update(name, value, comment?) - Update an existing variable
  • delete(name) - Delete a variable
  • has(name) - Check if a variable exists
  • clear() - Clear all variables, comments, and empty lines

Comments

  • addComment(comment) - Add a standalone comment
  • getComment(name) - Get a comment for a variable
  • updateComment(lineNum, comment) - Update a comment
  • deleteComment(lineNum) - Delete a comment
  • getAllComments() - Get all comments

Empty Lines

  • addEmpty() - Add an empty line
  • deleteEmpty(lineNum) - Delete an empty line

File Operations

  • save() - Save changes to file
  • parse() - Parse the .env file
  • getAll() - 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:

InputConverted 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.

FAQs

Package last updated on 25 Feb 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts