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

3 лет назад
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const fs = require('fs')
  2. const path = require('path')
  3. /*
  4. * Parses a string or buffer into an object
  5. * @param {(string|Buffer)} src - source to be parsed
  6. * @returns {Object} keys and values from src
  7. */
  8. function parse (src) {
  9. const obj = {}
  10. // convert Buffers before splitting into lines and processing
  11. src.toString().split('\n').forEach(function (line) {
  12. // matching "KEY' and 'VAL' in 'KEY=VAL'
  13. const keyValueArr = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/)
  14. // matched?
  15. if (keyValueArr != null) {
  16. const key = keyValueArr[1]
  17. // default undefined or missing values to empty string
  18. let value = keyValueArr[2] || ''
  19. // expand newlines in quoted values
  20. const len = value ? value.length : 0
  21. if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
  22. value = value.replace(/\\n/gm, '\n')
  23. }
  24. // remove any surrounding quotes and extra spaces
  25. value = value.replace(/(^['"]|['"]$)/g, '').trim()
  26. obj[key] = value
  27. }
  28. })
  29. return obj
  30. }
  31. /*
  32. * Main entry point into dotenv. Allows configuration before loading .env
  33. * @param {Object} options - options for parsing .env file
  34. * @param {string} [options.path=.env] - path to .env file
  35. * @param {string} [options.encoding=utf8] - encoding of .env file
  36. * @returns {Object} parsed object or error
  37. */
  38. function config (options) {
  39. let dotenvPath = path.resolve(process.cwd(), '.env')
  40. let encoding = 'utf8'
  41. if (options) {
  42. if (options.path) {
  43. dotenvPath = options.path
  44. }
  45. if (options.encoding) {
  46. encoding = options.encoding
  47. }
  48. }
  49. try {
  50. // specifying an encoding returns a string instead of a buffer
  51. const parsed = parse(fs.readFileSync(dotenvPath, { encoding }))
  52. Object.keys(parsed).forEach(function (key) {
  53. if (!process.env.hasOwnProperty(key)) {
  54. process.env[key] = parsed[key]
  55. }
  56. })
  57. return { parsed }
  58. } catch (e) {
  59. return { error: e }
  60. }
  61. }
  62. module.exports.config = config
  63. module.exports.load = config
  64. module.exports.parse = parse