Skip to content

Commit

Permalink
Merge 2e21d30 into ad86907
Browse files Browse the repository at this point in the history
  • Loading branch information
reginacarneiro committed Mar 10, 2018
2 parents ad86907 + 2e21d30 commit f148db8
Show file tree
Hide file tree
Showing 8 changed files with 1,941 additions and 878 deletions.
14 changes: 14 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"presets": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
]
}

2 changes: 1 addition & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
}
})

require('./lib/main').config(options)
require('./lib/index').config(options)
})()
79 changes: 79 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
'use strict';

var fs = require('fs');
var path = require('path');

/*
* Parses a string or buffer into an object
* @param {(string|Buffer)} src - source to be parsed
* @returns {Object} keys and values from src
*/
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] || '';

// 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;
}

/*
* Main entry point into dotenv. Allows configuration before loading .env
* @param {Object} options - options for parsing .env file
* @param {string} [options.path=.env] - path to .env file
* @param {string} [options.encoding=utf8] - encoding of .env file
* @returns {Object} parsed object or error
*/
function config(options) {
var dotenvPath = path.resolve(process.cwd(), '.env');
var encoding = 'utf8';

if (options) {
if (options.path) {
dotenvPath = options.path;
}
if (options.encoding) {
encoding = options.encoding;
}
}

try {
// specifying an encoding returns a string instead of a buffer
var parsed = parse(fs.readFileSync(dotenvPath, { encoding: encoding }));

Object.keys(parsed).forEach(function (key) {
if (!process.env.hasOwnProperty(key)) {
process.env[key] = parsed[key];
}
});

return { parsed: parsed };
} catch (e) {
return { error: e };
}
}

module.exports.config = config;
module.exports.load = config;
module.exports.parse = parse;
Loading

0 comments on commit f148db8

Please sign in to comment.