Skip to content

Instantly share code, notes, and snippets.

@zmts
Last active January 29, 2024 12:13
Show Gist options
  • Save zmts/239989508e5033710da126617509dabb to your computer and use it in GitHub Desktop.
Save zmts/239989508e5033710da126617509dabb to your computer and use it in GitHub Desktop.

Convert .env file to object

const isNumber = (value) => {
  return !isNaN(Number(value))
}

const getValue = (value) => {
  if (value === '') return value
  if (['true', 'false'].includes(value)) return JSON.parse(value)
  if (isNumber(value)) return Number(value)
  return value
}

const convertEnvToObject = (textString) => {
  const allRows = textString.split('\n').map(row => row.trim())
  const filteredRows = allRows.filter(i => i)

  const keyValueMap = filteredRows.reduce((acc, item) => {
    const parts = item.split('=')
    const key = parts[0]?.trim()
    const partValue = parts[1]?.trim()
    const value = getValue(partValue)

    if (typeof value !== 'undefined') acc[key] = value
    if (key?.startsWith('#')) acc[key] = ''
    return acc
  }, {})

  return keyValueMap
}
const text =`
# --- First comment ---
STRING_KEY=api.test.com
EMPTY_STRING=
BOOLEAN_TRUE=true
BOOLEAN_FALSE=false

# Second comment
ID=10     
COUNT=0
NUMBER=100
NUMBER_ZERO=0
NUMBER_NEGATIVE=-100
`

console.log(convertEnvToObject(text))

{
  '# --- First comment ---': '',
  STRING_KEY: 'api.test.com',
  EMPTY_STRING: '',
  BOOLEAN_TRUE: true,
  BOOLEAN_FALSE: false,
  '# Second comment': '',
  ID: 10,
  COUNT: 0,
  NUMBER: 100,
  NUMBER_ZERO: 0,
  NUMBER_NEGATIVE: -1000
}

Convert object to .env file

const convertObjectToEnv = (obj) => {
  let envString = ''
  for (const key in obj) {
    const value = obj[key]
    key.startsWith('#') ? (envString += `${key}\n`) : (envString += `${key}=${value}\n`)
  }
  return envString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment