npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

dotenv-handler

v1.3.0

Published

A lightweight helper for loading, setting, and saving environment variables using dotenv.

Downloads

675

Readme

dotenv-handler

dotenv-handler is a lightweight utility for managing environment variables in your Node.js applications. It provides an easy way to load, access, and manage environment variables with additional features like default values and required checks.

Installation

npm install dotenv-handler

or

pnpm add dotenv-handler

Usage

Load environment variables

import { loadConfig, getConfig } from 'dotenv-handler';

// Load configuration from .env file
loadConfig('.env', {
  // Set default values for environment variables
  defaults: {
    DEFAULT_KEY: 'defaultValue',
    // Expand must be set to true to use environment variables in default values
    DATABASE_URL: 'localhost:${PORT}/${DB_NAME}',
  },
  // Validate required environment variables
  required: ['PORT', 'DB_USER', 'DB_NAME'],
  // This will allow environment variables to be expanded
  expand: true,
  // Apply transformations to environment variables
  transformations: {
    PORT: value => parseInt(value, 10).toString(),
    DEFAULT_KEY: value => value.toUpperCase(),
  },
});

// Get configuration values
const port = getConfig('PORT');
const dbUser = getConfig('DB_USER');
const dbUrl = getConfig('DATABASE_URL');
console.log(`Server will run on port: ${port}`);
console.log(`Database user: ${dbUser}`);
console.log(`Database URL: ${dbUrl}`);

Set default values for environment variables

loadConfig('.env', {
  defaults: {
    DEFAULT_KEY: 'defaultValue',
  },
});

Validate required environment variables

loadConfig('.env', {
  required: ['PORT', 'DB_USER'],
});

Save environment variables to a file

import { setEnv, saveConfig } from 'dotenv-handler';

setEnv('NEW_KEY', 'newValue');
saveConfig('.env');

Expanding environment variables

loadConfig('.env', {
  defaults: {
    DB_HOST: 'localhost',
    DB_PORT: '5432',
    DATABASE_URL: '${DB_HOST}:${DB_PORT}/database',
  },
  // This will allow environment variables to be expanded
  expand: true,
  required: ['DATABASE_URL'],
});

const databaseUrl = getConfig('DATABASE_URL');
console.log(`Database URL: ${databaseUrl}`);

Apply custom validation logic

import { loadConfig, getConfig } from 'dotenv-handler';
import Joi from 'joi';

const schema = Joi.object({
  PORT: Joi.number().port().required(),
  DB_USER: Joi.string().required(),
  DB_NAME: Joi.string().required(),
});

loadConfig('.env', {
  required: ['PORT', 'DB_USER', 'DB_NAME'],
  validate: config => {
    const { error, value } = schema.validate(config);
    if (error) {
      throw new Error(`Invalid configuration: ${error.message}`);
    }
    return value;
  },
});

const port = getConfig('PORT');
const dbUser = getConfig('DB_USER');
const dbName = getConfig('DB_NAME');
console.log(`Server will run on port: ${port}`);
console.log(`Database user: ${dbUser}`);
console.log(`Database name: ${dbName}`);

Apply transformations to environment variables

loadConfig('.env', {
  // Apply transformations to environment variables
  transformations: {
    PORT: value => parseInt(value, 10).toString(),
    DB_USER: value => value.toUpperCase(),
  },
});

const port = getConfig('PORT');
const dbUser = getConfig('DB_USER');
console.log(`Server will run on port: ${port}`);
console.log(`Database user: ${dbUser}`);

Silence errors on missing required variables

loadConfig('.env', {
  required: ['PORT'],
  errorOnMissing: false,
});

Basic usage with CommonJS

const { loadConfig, getConfig } = require('dotenv-handler');

loadConfig('.env');

const port = getConfig('PORT');
console.log(`Server will run on port: ${port}`);

Use dotenv config object

import { loadConfig } from 'dotenv-handler';

loadConfig({ path: '.env.test' }, { required: ['PORT', 'DB_USER'] });

const port = getConfig('PORT');
const dbUser = getConfig('DB_USER');
console.log(`Server will run on port: ${port}`);
console.log(`Database user: ${dbUser}`);

API

loadConfig(envFilePathOrOptions: string | DotenvConfigOptions, options?: LoadConfigOptions): void

Loads environment variables from the specified file.

  • envFilePathOrOptions: Path to the file where environment variables are stored or a dotEnv config object.
  • options: An object with the following properties:
    • defaults: An object with default values for environment variables.
    • required: An array of environment variables that are required.
    • expand: A boolean value indicating whether to expand environment variables.
    • errorOnMissing: A boolean value indicating whether to throw an error if a required environment variable is missing.
    • transformations: An object with transformation functions for environment variables.
    • validate: A function that applies custom validation logic to the loaded configuration.

getConfig(key: string): string | undefined

Returns the value of the specified environment variable.

  • key: The name of the environment variable.

setEnv(key: string, value: string): void

Sets the value of the specified environment variable.

  • key: The
  • value: The value to set.

saveConfig(path: string): void

Saves the current environment variables to the specified file.

  • path: Path to the file where environment variables should be saved.

License

MIT