You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

295 lines
9.9 KiB

4 years ago
  1. # dotenv
  2. <img src="https://raw.githubusercontent.com/motdotla/dotenv/master/dotenv.png" alt="dotenv" align="right" />
  3. Dotenv 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.
  4. [![BuildStatus](https://img.shields.io/travis/motdotla/dotenv/master.svg?style=flat-square)](https://travis-ci.org/motdotla/dotenv)
  5. [![Build status](https://ci.appveyor.com/api/projects/status/github/motdotla/dotenv?svg=true)](https://ci.appveyor.com/project/motdotla/dotenv/branch/master)
  6. [![NPM version](https://img.shields.io/npm/v/dotenv.svg?style=flat-square)](https://www.npmjs.com/package/dotenv)
  7. [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard)
  8. [![Coverage Status](https://img.shields.io/coveralls/motdotla/dotenv/master.svg?style=flat-square)](https://coveralls.io/github/motdotla/dotenv?branch=coverall-intergration)
  9. ## Install
  10. ```bash
  11. # with npm
  12. npm install dotenv
  13. # or with Yarn
  14. yarn add dotenv
  15. ```
  16. ## Usage
  17. As early as possible in your application, require and configure dotenv.
  18. ```javascript
  19. require('dotenv').config()
  20. ```
  21. Create a `.env` file in the root directory of your project. Add
  22. environment-specific variables on new lines in the form of `NAME=VALUE`.
  23. For example:
  24. ```dosini
  25. DB_HOST=localhost
  26. DB_USER=root
  27. DB_PASS=s1mpl3
  28. ```
  29. That's it.
  30. `process.env` now has the keys and values you defined in your `.env` file.
  31. ```javascript
  32. const db = require('db')
  33. db.connect({
  34. host: process.env.DB_HOST,
  35. username: process.env.DB_USER,
  36. password: process.env.DB_PASS
  37. })
  38. ```
  39. ### Preload
  40. You can use the `--require` (`-r`) [command line option](https://nodejs.org/api/cli.html#cli_r_require_module) 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`.
  41. ```bash
  42. $ node -r dotenv/config your_script.js
  43. ```
  44. The configuration options below are supported as command line arguments in the format `dotenv_config_<option>=value`
  45. ```bash
  46. $ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars
  47. ```
  48. Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.
  49. ```bash
  50. $ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
  51. ```
  52. ```bash
  53. $ DOTENV_CONFIG_ENCODING=base64 node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
  54. ```
  55. ## Config
  56. _Alias: `load`_
  57. `config` will read your .env file, parse the contents, assign it to
  58. [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
  59. and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
  60. ```js
  61. const result = dotenv.config()
  62. if (result.error) {
  63. throw result.error
  64. }
  65. console.log(result.parsed)
  66. ```
  67. You can additionally, pass options to `config`.
  68. ### Options
  69. #### Path
  70. Default: `path.resolve(process.cwd(), '.env')`
  71. You may specify a custom path if your file containing environment variables is located elsewhere.
  72. ```js
  73. require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' })
  74. ```
  75. #### Encoding
  76. Default: `utf8`
  77. You may specify the encoding of your file containing environment variables.
  78. ```js
  79. require('dotenv').config({ encoding: 'base64' })
  80. ```
  81. #### Debug
  82. Default: `false`
  83. You may turn on logging to help debug why certain keys or values are not being set as you expect.
  84. ```js
  85. require('dotenv').config({ debug: process.env.DEBUG })
  86. ```
  87. ## Parse
  88. The engine which parses the contents of your file containing environment
  89. variables is available to use. It accepts a String or Buffer and will return
  90. an Object with the parsed keys and values.
  91. ```js
  92. const dotenv = require('dotenv')
  93. const buf = Buffer.from('BASIC=basic')
  94. const config = dotenv.parse(buf) // will return an object
  95. console.log(typeof config, config) // object { BASIC : 'basic' }
  96. ```
  97. ### Options
  98. #### Debug
  99. Default: `false`
  100. You may turn on logging to help debug why certain keys or values are not being set as you expect.
  101. ```js
  102. const dotenv = require('dotenv')
  103. const buf = Buffer.from('hello world')
  104. const opt = { debug: true }
  105. const config = dotenv.parse(buf, opt)
  106. // expect a debug message because the buffer is not in KEY=VAL form
  107. ```
  108. ### Rules
  109. The parsing engine currently supports the following rules:
  110. - `BASIC=basic` becomes `{BASIC: 'basic'}`
  111. - empty lines are skipped
  112. - lines beginning with `#` are treated as comments
  113. - empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
  114. - single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
  115. - new lines are expanded if in double quotes (`MULTILINE="new\nline"` becomes
  116. ```
  117. {MULTILINE: 'new
  118. line'}
  119. ```
  120. - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
  121. - 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'}`)
  122. ## FAQ
  123. ### Should I commit my `.env` file?
  124. No. We **strongly** recommend against committing your `.env` file to version
  125. control. It should only include environment-specific values such as database
  126. passwords or API keys. Your production database should have a different
  127. password than your development database.
  128. ### Should I have multiple `.env` files?
  129. No. 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.
  130. > 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.
  131. >
  132. > – [The Twelve-Factor App](http://12factor.net/config)
  133. ### What happens to environment variables that were already set?
  134. We 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.
  135. If you want to override `process.env` you can do something like this:
  136. ```javascript
  137. const fs = require('fs')
  138. const dotenv = require('dotenv')
  139. const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
  140. for (let k in envConfig) {
  141. process.env[k] = envConfig[k]
  142. }
  143. ```
  144. ### Can I customize/write plugins for dotenv?
  145. For `dotenv@2.x.x`: Yes. `dotenv.config()` now returns an object representing
  146. the parsed `.env` file. This gives you everything you need to continue
  147. setting values on `process.env`. For example:
  148. ```js
  149. const dotenv = require('dotenv')
  150. const variableExpansion = require('dotenv-expand')
  151. const myEnv = dotenv.config()
  152. variableExpansion(myEnv)
  153. ```
  154. ### What about variable expansion?
  155. Try [dotenv-expand](https://github.com/motdotla/dotenv-expand)
  156. ### How do I use dotenv with `import`?
  157. ES2015 and beyond offers modules that allow you to `export` any top-level `function`, `class`, `var`, `let`, or `const`.
  158. > 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.
  159. >
  160. > – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
  161. You must run `dotenv.config()` before referencing any environment variables. Here's an example of problematic code:
  162. `errorReporter.js`:
  163. ```js
  164. import { Client } from 'best-error-reporting-service'
  165. export const client = new Client(process.env.BEST_API_KEY)
  166. ```
  167. `index.js`:
  168. ```js
  169. import dotenv from 'dotenv'
  170. import errorReporter from './errorReporter'
  171. dotenv.config()
  172. errorReporter.client.report(new Error('faq example'))
  173. ```
  174. `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.
  175. 1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
  176. 2. 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_)
  177. 3. 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)
  178. ## Contributing Guide
  179. See [CONTRIBUTING.md](CONTRIBUTING.md)
  180. ## Change Log
  181. See [CHANGELOG.md](CHANGELOG.md)
  182. ## License
  183. See [LICENSE](LICENSE)
  184. ## Who's using dotenv
  185. Here's just a few of many repositories using dotenv:
  186. * [jaws](https://github.com/jaws-framework/jaws-core-js)
  187. * [node-lambda](https://github.com/motdotla/node-lambda)
  188. * [resume-cli](https://www.npmjs.com/package/resume-cli)
  189. * [phant](https://www.npmjs.com/package/phant)
  190. * [adafruit-io-node](https://github.com/adafruit/adafruit-io-node)
  191. * [mockbin](https://www.npmjs.com/package/mockbin)
  192. * [and many more...](https://www.npmjs.com/browse/depended/dotenv)
  193. ## Go well with dotenv
  194. Here's some projects that expand on dotenv. Check them out.
  195. * [require-environment-variables](https://github.com/bjoshuanoah/require-environment-variables)
  196. * [dotenv-safe](https://github.com/rolodato/dotenv-safe)
  197. * [envalid](https://github.com/af/envalid)
  198. * [lookenv](https://github.com/RodrigoEspinosa/lookenv)
  199. * [run.env](https://www.npmjs.com/package/run.env)
  200. * [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack)
  201. * [env-path](https://github.com/benrei/env-path)