genv-ex
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

genv-ex

A lightweight Node.js utility to generate a .env.example file from a .env file, replacing sensitive values with placeholders. Ideal for sharing environment variable templates in Node.js and full-stack projects.

📦 Simply (Recommended Usage)

✔️ Install locally

npm install genv-ex

✔️ Use in your code

CommonJS (default Node.js)

// index.js (CommonJS)
const genvex = require("genv-ex");

genvex();

ES Modules (with "type": "module" in package.json or using .mjs)

// index.js (ESM)
import genvex from "genv-ex";

genvex();

Features

  • Generates .env.example from .env with customizable placeholders.
  • Preserves comments and empty lines for better readability.
  • Supports preserving specific values or ignoring keys.
  • Configurable via CLI, programmatic API, or .genv-exrc file.
  • Handles large files efficiently with streaming.
  • Interactive CLI prompts for missing .env files.
  • CommonJS and ESM compatible.

Installation

Install locally in a project:

# install locally (recommended)
npm install genv-ex

Or globally for CLI use:

npm install -g genv-ex

For development with nodemon:

npm install --save-dev nodemon

File Structure

Ensure your project has the following structure:

your-project/
├── .env              # Source environment file
├── .genv-exrc        # Optional config file
├── node_modules/
├── package.json
└── genv-ex/          # If developing locally
    ├── index.js      # Main module
    ├── bin/
    │   └── cli.js    # CLI script

Usage

genv-ex can be used via the command-line interface (CLI) or programmatically in your Node.js code.

CLI Usage

Run genv-ex to generate .env.example from .env with default settings:

npx genv-ex

This reads .env, replaces values with <YOUR_VALUE_HERE>, and creates .env.example, preserving comments.

Common Commands

  • Specify input/output files:
    npx genv-ex -i .env.prod -o .env.prod.example
  • Preserve specific keys:
    npx genv-ex --preserve API_KEY PUBLIC_URL
  • Ignore keys:
    npx genv-ex --ignore SECRET_TOKEN
  • Exclude comments:
    npx genv-ex --no-comments
  • Preview without writing:
    npx genv-ex --dry-run
  • Create a sample .env:
    npx genv-ex --init

Interactive Mode

If no .env file exists, the CLI prompts to create a sample:

$ npx genv-ex
No '.env' file found.
Create a sample .env file? (y/n): y
Created '.env'. Edit it and run again.

Help

See all options:

npx genv-ex --help

Package Scripts

Add to package.json for convenience:

{
  "scripts": {
    "gen-env": "genv-ex",
    "start": "nodemon bin/cli.js"
  }
}

Run:

npm run gen-env

Programmatic Usage

Use genv-ex in your Node.js code for integration into scripts or applications.

CommonJS

// index.js
const generateEnvExample = require("genv-ex");

generateEnvExample()
  .then((result) => console.log("Generated:", result))
  .catch((error) => console.error("Error:", error.message));

Run:

node index.js

ESM

For ESM projects ("type": "module" in package.json):

// index.js
import generateEnvExample from "genv-ex";

async function run() {
  const result = await generateEnvExample({
    preserveValues: ["API_KEY"],
    ignoreKeys: ["SECRET"],
  });
  console.log("Generated:", result);
}

run();

package.json:

{
  "type": "module",
  "dependencies": {
    "genv-ex": "^1.0.0"
  }
}

Run:

node index.js

Example Output

For a .env file:

# Database config
API_KEY=xyz123
DATABASE_URL=mongodb://localhost:27017
SECRET=hidden

Running npx genv-ex --preserve API_KEY --ignore SECRET:

# Generated by genv-ex
# Auto-generated on 2025-04-12T12:34:56.789Z
# Database config
API_KEY=xyz123
DATABASE_URL=<YOUR_VALUE_HERE>

Console output:

Successfully created '.env.example' with 2 keys
Skipped keys: SECRET

Configuration File

Use a .genv-exrc file to set defaults (supports JSON5 for comments, trailing commas):

{
  // Default placeholder
  "placeholder": "YOUR_VALUE",
  // Preserve these keys
  "preserveValues": ["API_KEY", "PUBLIC_URL"],
  // Include comments
  "includeComments": true
}

CLI or programmatic options override .genv-exrc.

Options

Option Description Default
envFilePath Source .env file path .env
outputFilePath Output .env.example file path .env.example
placeholder Placeholder for values <YOUR_VALUE_HERE>
preserveValues Array of keys to keep original values []
ignoreKeys Array of keys to exclude []
includeComments Preserve comments and empty lines true
header Custom header text # Generated by genv-ex...
force Overwrite existing output file true
silent Suppress console output false
dryRun Preview output without writing false
configFile Path to config file .genv-exrc

CLI flags (e.g., --no-comments, --no-force) override defaults.

Running with Nodemon

For development, use nodemon to watch for changes:

npm run start

Tip: Add .env.example to .nodemonignore to prevent infinite loops:

.env.example

If you encounter crashes, ensure bin/cli.js exists and package.json scripts are correct.

Troubleshooting

  • No .env file:
    • Run npx genv-ex --init to create a sample.
    • Or create .env manually with API_KEY=your_key.
  • File not found:
    • Verify bin/cli.js exists in genv-ex/bin/.
    • Check package.json’s bin and scripts.
  • Nodemon crashes:
    • Run node bin/cli.js to isolate errors.
    • Ensure script points to bin/cli.js, not src/cli.js.
  • Permissions:
    • Run chmod +x bin/cli.js.
    • Check write access: chmod u+w ..
  • Dependencies:
    npm install dotenv json5 commander
    npm install --save-dev nodemon

Contributing

Contributions are welcome! To contribute:

  1. Fork the repository.
  2. Create a branch: git checkout -b feature/your-feature.
  3. Commit changes: git commit -m "Add your feature".
  4. Push: git push origin feature/your-feature.
  5. Open a pull request.

Please include tests and update this README.md.

License

Licensed under the MIT License. See LICENSE for details.

Package Sidebar

Install

npm i genv-ex

Weekly Downloads

1

Version

1.1.0

License

MIT

Unpacked Size

22 kB

Total Files

6

Last publish

Collaborators

  • dilakshan_pahitharan