Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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/rnba2pyi87hgc8xw/branch/master?svg=true)](https://ci.appveyor.com/project/maxbeatty/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 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. ## Config
  49. _Alias: `load`_
  50. `config` will read your .env file, parse the contents, assign it to
  51. [`process.env`](https://nodejs.org/docs/latest/api/process.html#process_process_env),
  52. and return an Object with a `parsed` key containing the loaded content or an `error` key if it failed.
  53. ```js
  54. const result = dotenv.config()
  55. if (result.error) {
  56. throw result.error
  57. }
  58. console.log(result.parsed)
  59. ```
  60. You can additionally, pass options to `config`.
  61. ### Options
  62. #### Path
  63. Default: `path.resolve(process.cwd(), '.env')`
  64. You can specify a custom path if your file containing environment variables is
  65. named or located differently.
  66. ```js
  67. require('dotenv').config({path: '/full/custom/path/to/your/env/vars'})
  68. ```
  69. #### Encoding
  70. Default: `utf8`
  71. You may specify the encoding of your file containing environment variables
  72. using this option.
  73. ```js
  74. require('dotenv').config({encoding: 'base64'})
  75. ```
  76. ## Parse
  77. The engine which parses the contents of your file containing environment
  78. variables is available to use. It accepts a String or Buffer and will return
  79. an Object with the parsed keys and values.
  80. ```js
  81. const dotenv = require('dotenv')
  82. const buf = Buffer.from('BASIC=basic')
  83. const config = dotenv.parse(buf) // will return an object
  84. console.log(typeof config, config) // object { BASIC : 'basic' }
  85. ```
  86. ### Rules
  87. The parsing engine currently supports the following rules:
  88. - `BASIC=basic` becomes `{BASIC: 'basic'}`
  89. - empty lines are skipped
  90. - lines beginning with `#` are treated as comments
  91. - empty values become empty strings (`EMPTY=` becomes `{EMPTY: ''}`)
  92. - single and double quoted values are escaped (`SINGLE_QUOTE='quoted'` becomes `{SINGLE_QUOTE: "quoted"}`)
  93. - new lines are expanded if in double quotes (`MULTILINE="new\nline"` becomes
  94. ```
  95. {MULTILINE: 'new
  96. line'}
  97. ```
  98. - inner quotes are maintained (think JSON) (`JSON={"foo": "bar"}` becomes `{JSON:"{\"foo\": \"bar\"}"`)
  99. - 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'}`)
  100. ## FAQ
  101. ### Should I commit my `.env` file?
  102. No. We **strongly** recommend against committing your `.env` file to version
  103. control. It should only include environment-specific values such as database
  104. passwords or API keys. Your production database should have a different
  105. password than your development database.
  106. ### Should I have multiple `.env` files?
  107. 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.
  108. > 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.
  109. >
  110. > – [The Twelve-Factor App](http://12factor.net/config)
  111. ### What happens to environment variables that were already set?
  112. 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.
  113. If you want to override `process.env` you can do something like this:
  114. ```javascript
  115. const fs = require('fs')
  116. const dotenv = require('dotenv')
  117. const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
  118. for (var k in envConfig) {
  119. process.env[k] = envConfig[k]
  120. }
  121. ```
  122. ### Can I customize/write plugins for dotenv?
  123. For `dotenv@2.x.x`: Yes. `dotenv.config()` now returns an object representing
  124. the parsed `.env` file. This gives you everything you need to continue
  125. setting values on `process.env`. For example:
  126. ```js
  127. var dotenv = require('dotenv')
  128. var variableExpansion = require('dotenv-expand')
  129. const myEnv = dotenv.config()
  130. variableExpansion(myEnv)
  131. ```
  132. ### What about variable expansion?
  133. For `dotenv@2.x.x`: Use [dotenv-expand](https://github.com/motdotla/dotenv-expand).
  134. For `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.
  135. ### How do I use dotenv with `import`?
  136. ES2015 and beyond offers modules that allow you to `export` any top-level `function`, `class`, `var`, `let`, or `const`.
  137. > 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.
  138. >
  139. > – [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/)
  140. You must run `dotenv.config()` before referencing any environment variables. Here's an example of problematic code:
  141. `errorReporter.js`:
  142. ```js
  143. import { Client } from 'best-error-reporting-service'
  144. export const client = new Client(process.env.BEST_API_KEY)
  145. ```
  146. `index.js`:
  147. ```js
  148. import dotenv from 'dotenv'
  149. import errorReporter from './errorReporter'
  150. dotenv.config()
  151. errorReporter.client.report(new Error('faq example'))
  152. ```
  153. `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.
  154. 1. Preload dotenv: `node --require dotenv/config index.js` (_Note: you do not need to `import` dotenv with this approach_)
  155. 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_)
  156. 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)
  157. ## Contributing Guide
  158. See [CONTRIBUTING.md](CONTRIBUTING.md)
  159. ## Change Log
  160. See [CHANGELOG.md](CHANGELOG.md)
  161. ## License
  162. See [LICENSE](LICENSE)
  163. ## Who's using dotenv
  164. Here's just a few of many repositories using dotenv:
  165. * [jaws](https://github.com/jaws-framework/jaws-core-js)
  166. * [node-lambda](https://github.com/motdotla/node-lambda)
  167. * [resume-cli](https://www.npmjs.com/package/resume-cli)
  168. * [phant](https://www.npmjs.com/package/phant)
  169. * [adafruit-io-node](https://github.com/adafruit/adafruit-io-node)
  170. * [mockbin](https://www.npmjs.com/package/mockbin)
  171. * [and many more...](https://www.npmjs.com/browse/depended/dotenv)
  172. ## Go well with dotenv
  173. Here's some projects that expand on dotenv. Check them out.
  174. * [require-environment-variables](https://github.com/bjoshuanoah/require-environment-variables)
  175. * [dotenv-safe](https://github.com/rolodato/dotenv-safe)
  176. * [envalid](https://github.com/af/envalid)
  177. * [lookenv](https://github.com/RodrigoEspinosa/lookenv)
  178. * [run.env](https://www.npmjs.com/package/run.env)
  179. * [dotenv-webpack](https://github.com/mrsteele/dotenv-webpack)