How to use the dotenv.parse function in dotenv

To help you get started, we’ve selected a few dotenv examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sanity-io / sanity / packages / @sanity / webpack-integration / src / v3 / index.js View on Github external
function tryReadDotEnv(studioRootPath, configEnv) {
  const envFile = path.join(studioRootPath, `.env.${configEnv}`)

  let parsed = {}
  try {
    // eslint-disable-next-line no-sync
    parsed = dotenv.parse(fs.readFileSync(envFile, {encoding: 'utf8'}))
  } catch (err) {
    if (err.code !== 'ENOENT') {
      // eslint-disable-next-line no-console
      console.error(`There was a problem processing the .env file (${envFile})`, err)
    }
  }

  return parsed
}
github zeit / now / src / util / dev / server.ts View on Github external
async getLocalEnv(fileName: string, base?: EnvConfig): Promise {
    // TODO: use the file watcher to only invalidate the env `dotfile`
    // once a change to the `fileName` occurs
    const filePath = join(this.cwd, fileName);
    let env: EnvConfig = {};
    try {
      const dotenv = await fs.readFile(filePath, 'utf8');
      this.output.debug(`Using local env: ${filePath}`);
      env = parseDotenv(dotenv);
    } catch (err) {
      if (err.code !== 'ENOENT') {
        throw err;
      }
    }
    try {
      this.validateEnvConfig(fileName, base || {}, env);
    } catch (err) {
      if (err instanceof MissingDotenvVarsError) {
        this.output.error(err.message);
        await this.exit();
      } else {
        throw err;
      }
    }
    return { ...base, ...env };
github Jordaneisenburger / fallback-studio / src / pwa-studio / packages / venia-concept / validate-environment.js View on Github external
default: true
        })
    };
    if (process.env.NODE_ENV !== 'production') {
        validation.MAGENTO_BACKEND_URL = url({
            desc: 'Public base URL of of Magento 2.3 instance.',
            example: 'https://magento2.vagrant65'
        });
        const { readFileSync } = require('fs');
        const path = require('path');
        const chalk = require('chalk');
        const dotenv = require('dotenv');
        let parsedEnv;
        const envPath = path.join(__dirname, '.env');
        try {
            parsedEnv = dotenv.parse(readFileSync(envPath));
            // don't use console.log, which writes to stdout. writing to stdout
            // interferes with webpack json output
            console.warn(
                chalk.green(
                    `Using environment variables from ${chalk.greenBright(
                        '.env'
                    )}`
                )
            );
            if (env.DEBUG || env.NODE_DEBUG) {
                console.warn(
                    '\n  ' +
                        require('util')
                            .inspect(parsedEnv, {
                                colors: true,
                                compact: false
github EOSIO / eosio-explorer / serve.js View on Github external
const express = require('express');
const path = require('path');
const app = express();
const postgres = require('./routers/postgres');

const openBrowser = require('./helpers/openBrowser');

const fs = require('fs');
const dotenv = require('dotenv');
dotenv.config();
const envConfig = fs.existsSync('.env.local') && dotenv.parse(fs.readFileSync('.env.local'));

if (envConfig){
  for (let k in envConfig) {
    process.env[k] = envConfig[k];
  }
}

const PORT = process.env.REACT_APP_APP_SERVE_PORT;

// If serve.js is called from yarn serve-clear, set lastTimestamp = current timestamp
const lastTimestamp = process.env.CLEARBROWSERSTORAGE ? Math.floor(new Date() / 1000) : "";

app.use((req, res, next) => {

  // Always assign a value to the lastTimestamp cookie, either current timestamp or an empty string.
  res.cookie("lastTimestamp", lastTimestamp );
github lkwdwrd / generator-vvv / generators / dump / index.js View on Github external
SITE_TITLE: this.install.title,
			TABLE_PREFIX: this.install.site.prefix || 'wp_',
		};
		if ( this.install.site.constants.MULTISITE ) {
			basicItems.INSTALL_BASE = this.install.site.base || '/';
		}

		// Default Constants
		defaultConstants = {
			WPCONST_DB_USER: 'wordpress',
			WPCONST_DB_PASSWORD: 'wordpress',
		};

		// Set up salts
		try {
			salts = this._generateSalts( envParse( this.fs.read( path.join( envPath, '.env' ) ) ) );
		} catch( e ) {
			salts = this._generateSalts();
		}

		// Compile the environment file string.
		env = _.chain( this.install.site.constants )
			.mapKeys( function ( item, key ) { return 'WPCONST_' + key; } )
			.defaults( defaultConstants )
			.assign( basicItems )
			.assign( this.install.site.env )
			.defaults( salts )
			.value();


		// example key vars.
		envExample = _.assign( _.clone( env ), this._generateSalts( {}, 'your_key_here' ) );
github flatsheet / flatsheet / lib / index.js View on Github external
title: 'flatsheet',
      email: 'hi@flatsheet.io',
      // if SITE_URL not set, assumes we are not in production:
      url: (process.env.SITE_URL || 'http://127.0.0.1:3333'),
      contact: 'flatsheet admin'
    }
  }, opts)

  var self = this
  this.site = opts.site

  var envFilePath = path.join((opts.dir || process.cwd()), '.env')

  if (fs.existsSync(envFilePath)) {
    var envFile = fs.readFileSync(envFilePath)
    var secrets = dotenv.parse(envFile)
  } else {
    var secrets = {
      SENDGRID_USER: process.env.SENDGRID_USER,
      SENDGRID_PASS: process.env.SENDGRID_PASS,
      SECRET_TOKEN: process.env.SECRET_TOKEN
    }
  }
  this.tokens = require('./tokens')({ secret: secrets.SECRET_TOKEN })

  /*
  * Set path for static files
  */

  this.staticFiles = opts.staticFiles || path.join(__dirname, '..', 'public')
  this.staticFileUrl = opts.staticFileUrl || '/public/'
github flatsheet / flatsheet / bin / update-accounts-to-uuid.js View on Github external
function ready () {

  var envFilePath = path.join(process.cwd(), '.env');
  var envFile = fs.readFileSync(envFilePath);
  this.secrets = dotenv.parse(envFile);
  var self = this;

  deleteSessionsResetsAndIndexes();
  updateAccountStream.bind(self)(flatsheet.accountdown.list(), function () {
    console.log("\nBegin sheets updates...");
    updateSheetsStream.bind(self)(flatsheet.sheets.list());
  });
}
github EricKit / nest-user-auth / src / config / config.service.ts View on Github external
constructor(filePath: string) {
    let file: Buffer | undefined;
    try {
      file = fs.readFileSync(filePath);
    } catch (error) {
      file = fs.readFileSync('development.env');
    }

    const config = dotenv.parse(file);
    this.envConfig = this.validateInput(config);
  }
github wenderjean / checkdotenv / lib / example.js View on Github external
const hasMissingVariables = (filename) => {

    const parsed = Dotenv.parse(read(filename));
    const diff = _.difference(Object.keys(parsed), Object.keys(process.env));
    return _.size(diff) > 0 ? diff : false;
};

dotenv

Loads environment variables from .env file

BSD-2-Clause
Latest version published 2 months ago

Package Health Score

94 / 100
Full package analysis