Name |
Date |
Size |
#Lines |
LOC |
||
---|---|---|---|---|---|---|
.. | - | - | ||||
lib/ | 12-May-2024 | - | 80 | 46 | ||
CHANGELOG.md | D | 12-May-2024 | 3 KiB | 97 | 64 | |
LICENSE | D | 12-May-2024 | 1.3 KiB | 24 | 19 | |
README.md | D | 12-May-2024 | 9.4 KiB | 258 | 176 | |
appveyor.yml | D | 12-May-2024 | 257 | 14 | 13 | |
config.js | D | 12-May-2024 | 255 | 12 | 10 | |
package.json | D | 12-May-2024 | 1.8 KiB | 74 | 73 |
README.md
1# dotenv 2 3<img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.png" alt="dotenv" align="right" /> 4 5Dotenv is a zero-dependency module that loads environment variables from a `.env` file into [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env). Storing configuration in the environment separate from code is based on [The Twelve-Factor App](http://12factor.net/config) methodology. 6 7[](https://travis-ci.org/motdotla/dotenv) 8[](https://ci.appveyor.com/project/maxbeatty/dotenv/branch/master) 9[](https://www.npmjs.com/package/dotenv) 10[](https://github.com/feross/standard) 11[](https://coveralls.io/github/motdotla/dotenv?branch=coverall-intergration) 12 13## Install 14 15```bash 16npm install dotenv --save 17``` 18 19## Usage 20 21As early as possible in your application, require and configure dotenv. 22 23```javascript 24require('dotenv').config() 25``` 26 27Create a `.env` file in the root directory of your project. Add 28environment-specific variables on new lines in the form of `NAME=VALUE`. 29For example: 30 31```dosini 32DB_HOST=localhost 33DB_USER=root 34DB_PASS=s1mpl3 35``` 36 37That's it. 38 39`process.env` now has the keys and values you defined in your `.env` file. 40 41```javascript 42const db = require('db') 43db.connect({ 44 host: process.env.DB_HOST, 45 username: process.env.DB_USER, 46 password: process.env.DB_PASS 47}) 48``` 49 50### Preload 51 52You can use the `--require` (`-r`) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using `import` instead of `require`. 53 54```bash 55$ node -r dotenv/config your_script.js 56``` 57 58The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value` 59 60```bash 61$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars 62``` 63 64## Config 65 66_Alias: `load`_ 67 68`config` will read your .env file, parse the contents, assign it to 69[`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env), 70and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed. 71 72```js 73const result = dotenv.config() 74 75if (result.error) { 76 throw result.error 77} 78 79console.log(result.parsed) 80``` 81 82You can additionally, pass options to `config`. 83 84### Options 85 86#### Path 87 88Default: `path.resolve(process.cwd(), '.env')` 89 90You can specify a custom path if your file containing environment variables is 91named or located differently. 92 93```js 94require('dotenv').config({path: '/full/custom/path/to/your/env/vars'}) 95``` 96 97#### Encoding 98 99Default: `utf8` 100 101You may specify the encoding of your file containing environment variables 102using this option. 103 104```js 105require('dotenv').config({encoding: 'base64'}) 106``` 107 108## Parse 109 110The engine which parses the contents of your file containing environment 111variables is available to use. It accepts a String or Buffer and will return 112an Object with the parsed keys and values. 113 114```js 115const dotenv = require('dotenv') 116const buf = new Buffer('BASIC=basic') 117const config = dotenv.parse(buf) // will return an object 118console.log(typeof config, config) // object { BASIC : 'basic' } 119``` 120 121### Rules 122 123The parsing engine currently supports the following rules: 124 125- `BASIC=basic` becomes `{BASIC: 'basic'}` 126- empty lines are skipped 127- lines beginning with `#` are treated as comments 128- empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`) 129- single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`) 130- new lines are expanded if in double quotes (`MULTILINE="new\nline"` becomes 131 132``` 133{MULTILINE: 'new 134line'} 135``` 136- inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`) 137- whitespace is removed from both ends of the value (see more on [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)) (`FOO=" some value "` becomes `{FOO: 'some value'}`) 138 139## FAQ 140 141### Should I commit my `.env` file? 142 143No. We **strongly** recommend against committing your `.env` file to version 144control. It should only include environment-specific values such as database 145passwords or API keys. Your production database should have a different 146password than your development database. 147 148### Should I have multiple `.env` files? 149 150No. We **strongly** recommend against having a "main" `.env` file and an "environment" `.env` file like `.env.test`. Your config should vary between deploys, and you should not be sharing values between environments. 151 152> In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime. 153> 154> – [The Twelve-Factor App](http://12factor.net/config) 155 156### What happens to environment variables that were already set? 157 158We will never modify any environment variables that have already been set. In particular, if there is a variable in your `.env` file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all `.env` configurations with a machine-specific environment, although it is not recommended. 159 160If you want to override `process.env` you can do something like this: 161 162```javascript 163const fs = require('fs') 164const dotenv = require('dotenv') 165const envConfig = dotenv.parse(fs.readFileSync('.env.override')) 166for (var k in envConfig) { 167 process.env[k] = envConfig[k] 168} 169``` 170 171### Can I customize/write plugins for dotenv? 172 173For `dotenv@2.x.x`: Yes. `dotenv.config()` now returns an object representing 174the parsed `.env` file. This gives you everything you need to continue 175setting values on `process.env`. For example: 176 177```js 178var dotenv = require('dotenv') 179var variableExpansion = require('dotenv-expand') 180const myEnv = dotenv.config() 181variableExpansion(myEnv) 182``` 183 184### What about variable expansion? 185 186For `dotenv@2.x.x`: Use [dotenv-expand](https://github.com/motdotla/dotenv-expand). 187 188For `dotenv@1.x.x`: We haven't been presented with a compelling use case for expanding variables and believe it leads to env vars that are not "fully orthogonal" as [The Twelve-Factor App](http://12factor.net/config) outlines.<sup>[[1](https://github.com/motdotla/dotenv/issues/39)][[2](https://github.com/motdotla/dotenv/pull/97)]</sup> Please open an issue if you have a compelling use case. 189 190### How do I use dotenv with `import`? 191 192ES2015 and beyond offers modules that allow you to `export` any top-level `function`, `class`, `var`, `let`, or `const`. 193 194> When you run a module containing an `import` declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed. 195> 196> – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) 197 198You must run `dotenv.config()` before referencing any environment variables. Here's an example of problematic code: 199 200`errorReporter.js`: 201 202```js 203import { Client } from 'best-error-reporting-service' 204 205export const client = new Client(process.env.BEST_API_KEY) 206``` 207 208`index.js`: 209 210```js 211import dotenv from 'dotenv' 212dotenv.config() 213 214import errorReporter from './errorReporter' 215errorReporter.client.report(new Error('faq example')) 216``` 217 218`client` will not be configured correctly because it was constructed before `dotenv.config()` was executed. There are (at least) 3 ways to make this work. 219 2201. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_) 2212. Import `dotenv/config` instead of `dotenv` (_Note: you do not need to call `dotenv.config()` and must pass options via the command line with this approach_) 2223. Create a separate file that will execute `config` first as outlined in [this comment on #133](https://github.com/motdotla/dotenv/issues/133#issuecomment-255298822) 223 224## Contributing Guide 225 226See [CONTRIBUTING.md](CONTRIBUTING.md) 227 228## Change Log 229 230See [CHANGELOG.md](CHANGELOG.md) 231 232## License 233 234See [LICENSE](LICENSE) 235 236## Who's using dotenv 237 238Here's just a few of many repositories using dotenv: 239 240* [jaws](https://github.com/jaws-framework/jaws-core-js) 241* [node-lambda](https://github.com/motdotla/node-lambda) 242* [resume-cli](https://www.npmjs.com/package/resume-cli) 243* [phant](https://www.npmjs.com/package/phant) 244* [adafruit-io-node](https://github.com/adafruit/adafruit-io-node) 245* [mockbin](https://www.npmjs.com/package/mockbin) 246* [and many more...](https://www.npmjs.com/browse/depended/dotenv) 247 248## Go well with dotenv 249 250Here's some projects that expand on dotenv. Check them out. 251 252* [require-environment-variables](https://github.com/bjoshuanoah/require-environment-variables) 253* [dotenv-safe](https://github.com/rolodato/dotenv-safe) 254* [envalid](https://github.com/af/envalid) 255* [lookenv](https://github.com/RodrigoEspinosa/lookenv) 256* [run.env](https://www.npmjs.com/package/run.env) 257* [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack) 258