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
}