Giter Club home page Giter Club logo

deno-dotenv's Introduction

DEPRECATED: Dotenv is now a part of deno_std ๐ŸŽ‰

As of 0.127.0 dotenv is a part of the deno standard library.

Head to https://deno.land/std/dotenv to get started.

This repo is no longer maintained.

deno-dotenv's People

Contributors

ayame113 avatar gewoonwoutje avatar jsejcksn avatar keawade avatar pietbot avatar pietvanzoen avatar rahmanfadhil avatar rista404 avatar zinthose avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

deno-dotenv's Issues

Clarify env order preference

I am facing an issue where the ENV variable I am passing via the CLI is ignored in favour of .env

.env
MODE=dev
MODE=prod deno run --allow-read --allow-env main.ts
// main.ts
import 'https://deno.land/x/[email protected]/load.ts';
const mode = Deno.env.get('MODE')

console.log(mode) // dev

dotenv-expand-like variable expansion

Hi, thank you for an excellent library that works intuitively.

I'm working on a fairly complex project with a lot of variables inside the .env file. Is there intent to add the functionality of something like https://github.com/motdotla/dotenv-expand to expand the .env file variables so that when using them in deno, the environment variable values are fully expanded?

Thank you in advance.

.env variables are not loading into Deno.env

Issue

deno-donenv is not loading variables into Deno.env

File Structure:

project/
โ”œโ”€โ”€ .env
โ”œโ”€โ”€ import_map.json
โ””โ”€โ”€ src/
    โ””โ”€โ”€ app.js

Files

// import_map.json
{
  "imports": {
    "dotenv": "https://deno.land/x/dotenv/mod.ts"
  }
}
# .env
TEST=helloworld
// index.js
import { config } from 'dotenv'

config({
  path: '../.env',
  export: true,
})

console.log('TEST: ', Deno.env.get('TEST'))

Run Command & Output

I'm running this command from the root of my project

$ deno run --import-map=import_map.json --allow-read --allow-net --allow-env ./src/index.js
TEST: undefined

Warning: Implicitly using latest version (v3.0.0) for https://deno.land/x/dotenv/mod.ts

Platform:

  • Windows 10
  • Using Ubuntu 20.4 on WSL 2.0, essentially a Linux distr for Windows OS
  • Text Editor: VS Code
  • deno 1.14.2 (release, x86_64-unknown-linux-gnu)
  • v8 9.4.146.16
  • typescript 4.4.2

On top of my file, I use a standard import statement:

import { config } from "https://deno.land/x/dotenv/mod.ts"

const env = config({ safe: true, export: true })

Tried directly on Windows without using a VM and no matter what I do, I aways get the above warning.

Any pointers?

Feature Request: JSON to Object

I'm going to tinker with support to directly import JSON as an object to the returned config object.
Headers={Accept:="application/json", "Content-Type": "application/json;charset=UTF-8"}
would become:

console.log(config["Headers"])
{
  Accept: "application/json",
  "Content-Type": "application/json;charset=UTF-8"
}

I'll send a pull request when I'm happy with it.

Modify parser's whitespace handling

Hello. I have found a bug with the current parser. Here is an example:

% cat .env
# tests
LF_BARE=hello\nworld
LF_DQ="hello\nworld"
LF_SQ='hello\nworld'

CRLF_BARE=hello\r\nworld
CRLF_DQ="hello\r\nworld"
CRLF_SQ='hello\r\nworld'

TRIM_BARE= hello world 
TRIM_DQ=" hello world "
TRIM_DQ2= " hello world " 
TRIM_SQ=' hello world '
TRIM_SQ2= ' hello world ' 

% cat example.ts
import {config} from 'https://deno.land/x/[email protected]/mod.ts';
console.log(config());

% deno run --allow-read=.env example.ts
{
  LF_BARE: "hello\\nworld",
  LF_DQ: "hello\nworld",
  LF_SQ: "hello\\nworld",
  CRLF_BARE: "hello\\r\\nworld",
  CRLF_DQ: "hello\\r\nworld",
  CRLF_SQ: "hello\\r\\nworld",
  TRIM_BARE: "hello world",
  TRIM_DQ: "hello world",
  TRIM_DQ2: "hello world",
  TRIM_SQ: "hello world",
  TRIM_SQ2: "hello world"
}

For all of the keys which begin with TRIM_ (except for TRIM_BARE), the results are not what is expected.

If a value is not quoted, then I understand that trimming leading and trailing whitespace is desirable, but for quoted values, this should not be the case, since it makes it impossible to define values including whitespace at the ends.

I think this module is based on the Node dotev module, right? Here is a reference to its parsing rules:

Rules

The parsing engine currently supports the following rules:

  • BASIC=basic becomes {BASIC: 'basic'}
  • empty lines are skipped
  • lines beginning with # are treated as comments
  • empty values become empty strings (EMPTY= becomes {EMPTY: ''})
  • inner quotes are maintained (think JSON) (JSON={"foo": "bar"} becomes {JSON:"{\"foo\": \"bar\"}")
  • whitespace is removed from both ends of unquoted values (see more on trim) (FOO= some value becomes {FOO: 'some value'})
  • single and double quoted values are escaped (SINGLE_QUOTE='quoted' becomes {SINGLE_QUOTE: "quoted"})
  • single and double quoted values maintain whitespace from both ends (FOO=" some value " becomes {FOO: ' some value '})
  • double quoted values expand new lines (MULTILINE="new\nline" becomes
{MULTILINE: 'new
line'}

Also, I'm not sure how the original Node module handles CRLFs in quoted values, but (as you can see in the example) this module does not convert double-quoted CRLF (\\r\\n) to \r\n โ€” only the LFs. Perhaps this can be changed as well.

Load file

/load.ts that would trigger config({ export: true }). Allowing you to do:

import โ€œhttps://deno.land/x/dotenv/load.tsโ€

overwrite env files with envvar

If you have an .env file with a value set but then set an env var whilst running deno it is not overwritten.

in deployment cases often, envvars will be set as part of deployment for prod secrets that you may not want in files in source control

TwitterApiKey=233

TwitterApiKey=456 deno run --allow-read --allow-env mod.ts

console.log(dotenvConfig.TwitterApiKey) = 233 but I would expect it to be 456

Async version of "config()"

In other words, to use readFile() instead of readFileSync()โ€ฆ
That will make the whole thing async of courseโ€ฆ
So maybe make two versions config() and configSync()

Cannot import the dependency.

Hi, I'm using Deno 1.5.1 and when I try to import the dependency I'm getting every time this error :

warning: Compiled module not found "https://deno.land/x/dotenv/mod.ts"
  From: file:///C:/Users/Pierre/WebstormProjects/deno/tsc-bot/deps.ts
    If the source module contains only types, use `import type` and `export type` to import it instead.
error: Uncaught SyntaxError: The requested module 'https://deno.land/x/dotenv/mod.ts' does not provide an export named 'config'

This is the code : import { config } from "https://deno.land/x/dotenv/mod.ts";

`safe` option

Similar to dotenv-safe. Define template .env such as .env.example and use it to define required config. If a variable is missing throw an error.

dotenv does not load variables to Deno.env

deno --version output

deno 1.12.2 (release, x86_64-apple-darwin)
v8 9.2.230.14
typescript 4.3.5

.env file

# .env
HELLOWORLD=hello world

testenv.ts

import { config } from "https://deno.land/x/[email protected]/mod.ts";

console.log(Deno.env.get("HELLOWORLD"));
console.log(config());

output of deno run -A testenv.ts

undefined
{ HELLOWORLD: "hello world" }

Though it loads it to the config method output

TypeError: Deno.readFileSync is not a function

Getting this on deno deploy when loading config:

TypeError: Deno.readFileSync is not a function
    at parseFile (https://deno.land/x/[email protected]/mod.ts:103:59)
    at config (https://deno.land/x/[email protected]/mod.ts:42:18)

No issues when running locally.

The cause of this issue might be that

only stable APIs of Deno are made available in Deploy.

and Deno.readFileSync is not (yet) part of the stable API.
See https://deno.com/deploy/docs/runtime-api#deno-apis

This should be fixable by replacing Deno.readFileSync with await Deno.readFile and making the consuming method async.

Underscore is parsed as whitespace

As the title says, when I put an underscore in the value, it will get parsed as whitespace:

#./.env
KEY=SOME_VALUE
// ... config({})
console.log(Deno.env.get("KEY")) // => "SOME VALUE"

error: Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum

I have just two files list below, after Deno.env.get got 8083 from .env. But got an error. What can I do?

Edited: when I comment out all the dotenv related code, still got this error. Maybe it is not deno-dotenv problem, but I asked here to see if anyone knows what can I do.

Edited final: I know why is going wrong here... it must need to code: parseInt(Deno.env.get('PORT') so the new App(PORT) can be worked... I will close this issue later, Sorry to bother you!

server.ts

import { Application } from "https://deno.land/x/oak/mod.ts"
import 'https://deno.land/x/dotenv/load.ts'
const PORT = Deno.env.get('PORT')

console.log(PORT)

export class App {
  public app: Application
  public port: number
  public logger: any

  constructor(port: any) {
    this.app = new Application()
    this.port = port

    this.initializeMiddleware()
  }

  private initializeMiddleware() {
    this.app.use(async (ctx, next) => {
      await next()
      const rt = ctx.response.headers.get("X-Response-Time")
      console.log(`${ctx.request.method} ${ctx.request.url} - ${rt}`)
    })
  }

  public async listen() {
    console.log("Server is listening at http://localhost:", this.port)
    return await this.app.listen({ port: this.port })
  }
}

const app = new App(PORT)
app.listen()

.env

PORT=8083

error message

Server is listening at http://localhost: 8083
error: Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum
    at unwrapResponse ($deno$/ops/dispatch_json.ts:42:11)
    at Object.sendSync ($deno$/ops/dispatch_json.ts:69:10)
    at Object.listen ($deno$/ops/net.ts:51:10)
    at Object.listen ($deno$/net.ts:155:22)
    at listen ($deno$/net_unstable.ts:36:12)
    at Application.serve (https://deno.land/[email protected]/http/server.ts:252:20)
    at Application.listen (https://deno.land/x/oak/application.ts:295:20)
    at App.listen (app.ts:40:27)
    at server.ts:12:5

Deno Version

deno 1.1.3
v8 8.5.216
typescript 3.9.2

Deserialize config into type

Have you considered providing an option something like the below that allows strongly typed config?

import {config} from "https://deno.land/x/dotenv/mod.ts";

const appConfig = config<MyAppConfig>({ safe: true });

console.log(appConfig.MySecret);
console.log(appConfig.TwitterApiKey);
#.env file
MySecret=
TWITTERAPIKey=
type MyAppConfig = {
  MySecret:string
  TwitterApiKey:string
}

Support updating .env file

This is a request for a new module export for updating a .env file with a new key/value pair.

It would overwrite an existing entry with a matching key or add a new entry if one does not already exist.

Here's an example which uses the name update (although I'm not necessarily prescribing that name):

.env:

LOCATION=world

script.ts:

import {update} from 'https://deno.land/x/dotenv/mod.ts';

update('LOCATION', 'Earth');
update('GREETING', 'Hello');
> cat .env
LOCATION=world

> deno run script.ts

> cat .env
LOCATION=Earth
GREETING=Hello

There are obviously other considerations involved which are not shown in the example (e.g. configuring path to .env file), and even more considerations which would be implementation details (preserving unparsed data like comments in the file during overwrite, escaping certain strings, etc.). This comment is just to communicate the concept.

When setting safe env access is required

If you try and run the code the following code with the command deno run --allow-read test.ts it succeeds.

import { config } from "https://deno.land/x/dotenv/mod.ts";

console.log(config());

However, if you use the same command but run the following code it crashes with the error also included below.

import { config } from "https://deno.land/x/dotenv/mod.ts";

console.log(config({ safe: true }));
error: Uncaught PermissionDenied: Requires env access to all, run again with the --allow-env flag
    at Object.opSync (deno:core/01_core.js:149:12)
    at Object.toObject (deno:runtime/js/30_os.js:81:19)
    at assertSafe (https://deno.land/x/[email protected]/mod.ts:174:31)
    at processConfig (https://deno.land/x/[email protected]/mod.ts:114:5)
    at config (https://deno.land/x/[email protected]/mod.ts:63:10)
    at file:///[REDACTED]/test.ts:3:13

I don't understand why the inclusion of the safe parameter would require environment variable access. I am building a small webserver and would prefer to only load environment variables from disk and not allow direct environment variable access to Deno.

Thanks for this awesome module!

Adding variables within .env files

Typically .env these files are small and manageable, but there are times when you run into situations where you duplicate the same data within the file. Here is an example:

MAIL_USERNAME=[email protected]
MAIL_FROM_ADDRESS=[email protected]

The dotenv package that Laravel relies on can use variables with other defined variables in this same file. For example:

MAIL_USERNAME=[email protected]
MAIL_FROM_ADDRESS=${MAIL_USERNAME}

This simple trick allows you not to repeat yourself and can be useful when you have multiple services requiring the same piece of data.

I tried using this with the deno dotenv package and the engine doesn't pick up the variable, intead the console log value in the MAIL_FROM_ADDRESS example above would be ${MAIL_USERNAME} instead of [email protected].

Parsing numbers, booleans and null values

Hi,

First off, I like how easy it is with this package to import .env values into my project. However, I've noticed in my test projects, I'll would like it if true/false are parsed as boolean, numbers are correctly parsed, empty values are null or undefined instead of an empty string.

Right now I add the following code to my projects:

import {config} from "https://deno.land/x/[email protected]/mod.ts";

type EnvValue = null|number|boolean|string

type EnvObject = {
    [key: string]: EnvValue
}

export const env = Object.entries(config())
    .reduce((envObj: EnvObject, [key, value]: [string, string]) => {
        if(value === "" || value === "null") {
            envObj[key] = null;
        } else if (/^true|false$/i.test(value)) {
            envObj[key] = JSON.parse(value.toLowerCase());
        } else if (/^(\d*\.?\d+)$/.test(value)) {
            envObj[key] = parseFloat(value);
        } else {
            envObj[key] = value;
        }

        return envObj;
    }, {});

How would you look at the idea of implementing this something along the line of:

config({parseTypes: true});

deno 0.42.0 error

I use deno 0.42.0 with this lib, it got error.
I think this lib needs to be update

Deploy to a better location

Currently I'm just hosting via raw.githubusercontent.com. Would be nice to have a more concise url.

Options:

  • host on npm and use unpkg.com
  • proxy of some sort

config() returns an empty {}

Following this doc.

In .env

GREETING = Hello Deno
PORT = 8777
...

In app.ts

import { config } from "https://deno.land/x/dotenv/mod.ts";
console.log(config());

When I run:

$ cat .env
GREETING = Hello Deno
PORT = 8777
...
$ deno run --allow-read --allow-env app.ts
{}

What am I missing or doing wrong here?

Adding the ability to have return lines in .env files\

Being able to do actual return lines, and not having to do a \n for new lines would be great for .env files.

For example when building a Dockerfile, I don't want to have to:

DOCKER_CONTENTS='FROM node:8.11.4\nRUN mkdir -p /usr/app\nCOPY .'

It would be nice to do this instead:

DOCKER_CONTENTS="
FROM node:8.11.4 /
RUN mkdir -p /usr/app
COPY .
"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.