UNPKG

2.86 kBJavaScriptView Raw
1var fs = require('fs')
2var cons = require('./console').Console
3
4function method(name) {
5 return function(o) {
6 return o[name].apply(o)
7 }
8}
9
10// Parse a Key=Value File Containing Environmental Variables
11function KeyValue(data) {
12 var env = {};
13
14 data.toString().replace(/^\s*\#.*$/gm,'')
15 .replace(/^\s*$/gm,'')
16 .split(/\n/)
17 .map(method('trim'))
18 .filter(notBlank)
19 .forEach(capturePair)
20 return env
21
22 function notBlank(str) {
23 return str.length > 2
24 }
25
26 function capturePair(line) {
27 var pair = line.split('=');
28 var key = pair[0].trim();
29 var rawVal = pair.slice(1).join('=').trim();
30 env[key] = parseValue(rawVal);
31 }
32
33 function parseValue(val) {
34 switch (val[0]) {
35 case '"': return /^"([^"]*)"/.exec(val)[1];
36 case "'": return /^'([^']*)'/.exec(val)[1];
37 default : return val.replace(/\s*\#.*$/, '');
38 }
39 }
40}
41
42// Given:
43/*
44{
45 "top": {
46 "middle": {
47 "bottom": "value"
48 },
49 "other": [ "zero", "one", "two" ]
50 },
51 "last": 42
52}
53*/
54// Get:
55/*
56{
57 "TOP_MIDDLE_BOTTOM": "value",
58 "TOP_OTHER_0": "zero",
59 "TOP_OTHER_1": "one",
60 "TOP_OTHER_2": "two",
61 "LAST": 42
62}
63*/
64// Flatten nested object structure
65function flattenJSON(json) {
66 var flattened = {}
67
68 walk(json, function(path, item) {
69 flattened[path.join('_').toUpperCase()] = item
70 })
71
72 return flattened
73
74 function walk(obj, visitor, path) {
75 var item
76 path = path || []
77 for (key in obj) {
78 item = obj[key]
79 if (typeof item == 'object') {
80 walk(item, visitor, path.concat(key))
81 } else {
82 visitor(path.concat(key), item)
83 }
84 }
85 }
86}
87
88
89// Given a standard dictionary:
90/*
91{
92 "TOP_MIDDLE_BOTTOM": "value",
93 "TOP_OTHER_0": "zero",
94 "TOP_OTHER_1": "one",
95 "TOP_OTHER_2": "two",
96 "LAST": 42
97}
98*/
99// Return a key=value pair document
100/*
101TOP_MIDDLE_BOTTOM=value
102TOP_OTHER_0=zero
103TOP_OTHER_1=one
104TOP_OTHER_2=two
105LAST=42
106*/
107function dumpEnv(conf) {
108 var output = []
109 for (key in conf) {
110 output.push(key + '=' + conf[key])
111 }
112 return output.join('\n') + '\n'
113}
114
115// Loads a file as either a .env format or JSON format and returns it as a
116// simplified dictionary
117function loadEnvs(path){
118 var env, data
119
120 if (!fs.existsSync(path)) {
121 cons.Warn("No ENV file found")
122 env = {}
123 } else {
124 data = fs.readFileSync(path);
125 try {
126 var envs_json = JSON.parse(data)
127 env = flattenJSON(envs_json,"",{});
128 cons.Alert("Loaded ENV %s File as JSON Format",path);
129 } catch (e) {
130 env = KeyValue(data);
131 cons.Alert("Loaded ENV %s File as KEY=VALUE Format",path);
132 }
133 }
134 env.PATH = env.PATH || process.env.PATH;
135 return env;
136}
137
138module.exports.loadEnvs = loadEnvs
139module.exports.flattenJSON = flattenJSON
140module.exports.KeyValue = KeyValue
141module.exports.dumpEnv = dumpEnv