main.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict'
  2. var dotenvExpand = function (config) {
  3. // if ignoring process.env, use a blank object
  4. var environment = config.ignoreProcessEnv ? {} : process.env
  5. var interpolate = function (envValue) {
  6. var matches = envValue.match(/(.?\${?(?:[a-zA-Z0-9_]+)?}?)/g) || []
  7. return matches.reduce(function (newEnv, match) {
  8. var parts = /(.?)\${?([a-zA-Z0-9_]+)?}?/g.exec(match)
  9. var prefix = parts[1]
  10. var value, replacePart
  11. if (prefix === '\\') {
  12. replacePart = parts[0]
  13. value = replacePart.replace('\\$', '$')
  14. } else {
  15. var key = parts[2]
  16. replacePart = parts[0].substring(prefix.length)
  17. // process.env value 'wins' over .env file's value
  18. value = environment.hasOwnProperty(key) ? environment[key] : (config.parsed[key] || '')
  19. // Resolve recursive interpolations
  20. value = interpolate(value)
  21. }
  22. return newEnv.replace(replacePart, value)
  23. }, envValue)
  24. }
  25. for (var configKey in config.parsed) {
  26. var value = environment.hasOwnProperty(configKey) ? environment[configKey] : config.parsed[configKey]
  27. config.parsed[configKey] = interpolate(value)
  28. }
  29. for (var processKey in config.parsed) {
  30. environment[processKey] = config.parsed[processKey]
  31. }
  32. return config
  33. }
  34. module.exports = dotenvExpand