function config(options) {
var path = '.env'
var encoding = 'utf8'
if (options) {
if (options.path) {
path = options.path
}
if (options.encoding) {
encoding = options.encoding
}
}
try {
// specifying an encoding returns a string instead of a buffer
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 }
}
}...
process.argv.forEach(function (val, idx, arr) {
var matches = val.match(/^dotenv_config_(.+)=(.+)/)
if (matches) {
options[matches[1]] = matches[2]
}
})
require('./lib/main').config(options)
})()
...function config(options) {
var path = '.env'
var encoding = 'utf8'
if (options) {
if (options.path) {
path = options.path
}
if (options.encoding) {
encoding = options.encoding
}
}
try {
// specifying an encoding returns a string instead of a buffer
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 }
}
}n/a
function parse(src) {
var obj = {}
// convert Buffers before splitting into lines and processing
src.toString().split('\n').forEach(function (line) {
// matching "KEY' and 'VAL' in 'KEY=VAL'
var keyValueArr = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/)
// matched?
if (keyValueArr != null) {
var key = keyValueArr[1]
// default undefined or missing values to empty string
var value = keyValueArr[2] ? keyValueArr[2] : ''
// expand newlines in quoted values
var len = value ? value.length : 0
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, '\n')
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim()
obj[key] = value
}
})
return obj
}...
The engine which parses the contents of your file containing environment
variables is available to use. It accepts a String or Buffer and will return
an Object with the parsed keys and values.
```js
var dotenv = require('dotenv')
var buf = new Buffer('BASIC=basic')
var config = dotenv.parse(buf) // will return an object
console.log(typeof config, config) // object { BASIC : 'basic' }
```
### Rules
The parsing engine currently supports the following rules:
...