|
'use strict' |
|
|
|
var fs = require('fs') |
|
|
|
|
|
|
|
|
|
|
|
|
|
function parse (src) { |
|
var obj = {} |
|
|
|
|
|
src.toString().split('\n').forEach(function (line) { |
|
|
|
var keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/) |
|
|
|
if (keyValueArr != null) { |
|
var key = keyValueArr[1] |
|
|
|
|
|
var value = keyValueArr[2] ? keyValueArr[2] : '' |
|
|
|
|
|
var len = value ? value.length : 0 |
|
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') { |
|
value = value.replace(/\\n/gm, '\n') |
|
} |
|
|
|
|
|
value = value.replace(/(^['"]|['"]$)/g, '').trim() |
|
|
|
obj[key] = value |
|
} |
|
}) |
|
|
|
return obj |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function config (options) { |
|
var path = '.env' |
|
var encoding = 'utf8' |
|
|
|
if (options) { |
|
if (options.path) { |
|
path = options.path |
|
} |
|
if (options.encoding) { |
|
encoding = options.encoding |
|
} |
|
} |
|
|
|
try { |
|
|
|
var parsedObj = parse(fs.readFileSync(path, { encoding: encoding })) |
|
|
|
Object.keys(parsedObj).forEach(function (key) { |
|
process.env[key] = process.env[key] || parsedObj[key] |
|
}) |
|
|
|
return { parsed: parsedObj } |
|
} catch (e) { |
|
return { error: e } |
|
} |
|
} |
|
|
|
module.exports.config = config |
|
module.exports.load = config |
|
module.exports.parse = parse |
|
|