Skip to content

Commit b5e994d

Browse files
authored
Merge pull request #15 from ctavan/modernize
Modernize code (Node.js >= 6.0)
2 parents 82cb9fd + 9e12798 commit b5e994d

File tree

12 files changed

+450
-393
lines changed

12 files changed

+450
-393
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules/
2+
*.log

.travis.yml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
language: node_js
22

33
node_js:
4-
- 0.8
4+
- 6
5+
- 8
6+
- 10
7+
- 12

LICENSE.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
The MIT License (MIT)
2+
Copyright (c) 2012-2019 Christoph Tavan <[email protected]>
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy
5+
of this software and associated documentation files (the "Software"), to deal
6+
in the Software without restriction, including without limitation the rights
7+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8+
copies of the Software, and to permit persons to whom the Software is
9+
furnished to do so, subject to the following conditions:
10+
11+
The above copyright notice and this permission notice shall be included in all
12+
copies or substantial portions of the Software.
13+
14+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20+
SOFTWARE.

Makefile

Lines changed: 0 additions & 4 deletions
This file was deleted.

README.md

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ Helper to get and typecast environment variables. This is especially useful if y
1010
npm install getenv
1111
```
1212

13+
TypeScript types are available from the `@types/getenv` module.
14+
1315
## Usage
1416

1517
Set environment variables:
@@ -26,31 +28,31 @@ export PRIMES="2,3,5,7"
2628
Get and use them:
2729

2830
```javascript
29-
var getenv = require('getenv');
31+
const getenv = require('getenv');
3032

31-
var host = getenv('HTTP_HOST'); // same as getenv.string('HTTP_HOST');
32-
var port = getenv.int('HTTP_PORT');
33-
var start = getenv.bool('HTTP_START');
33+
const host = getenv('HTTP_HOST'); // same as getenv.string('HTTP_HOST');
34+
const port = getenv.int('HTTP_PORT');
35+
const start = getenv.bool('HTTP_START');
3436

3537
if (start === true) {
36-
// var server = http.createServer();
38+
// const server = http.createServer();
3739
// server.listen(port, host);
3840
}
3941

40-
var abTestRatio = getenv.float('AB_TEST_RATIO');
42+
const abTestRatio = getenv.float('AB_TEST_RATIO');
4143

4244
if (Math.random() < abTestRatio) {
4345
// test A
4446
} else {
4547
// test B
4648
}
4749

48-
var keywords = getenv.array('KEYWORDS');
50+
const keywords = getenv.array('KEYWORDS');
4951
keywords.forEach(function(keyword) {
5052
// console.log(keyword);
5153
});
5254

53-
var primes = getenv.array('PRIMES', 'int');
55+
const primes = getenv.array('PRIMES', 'int');
5456
primes.forEach(function(prime) {
5557
// console.log(prime, typeof prime);
5658
});
@@ -93,21 +95,20 @@ Split value of the environment variable at each comma and return the resulting a
9395
Return a list of environment variables based on a `spec`:
9496

9597
```javascript
96-
var config = getenv.multi({
97-
foo: "FOO", // throws if FOO doesn't exist
98-
bar: ["BAR", "defaultval"], // set a default value
99-
baz: ["BAZ", "defaultval", "string"], // parse into type
100-
quux: ["QUUX", undefined, "int"] // parse & throw
98+
const config = getenv.multi({
99+
foo: 'FOO', // throws if FOO doesn't exist
100+
bar: ['BAR', 'defaultval'], // set a default value
101+
baz: ['BAZ', 'defaultval', 'string'], // parse into type
102+
quux: ['QUUX', undefined, 'int'], // parse & throw
101103
});
102-
103104
```
104105

105106
### env.url(name, [fallback])
106107

107108
Return a parsed URL as per Node's `require("url").parse`. N.B `url` doesn't validate URLs, so be sure it includes a protocol or you'll get deeply weird results.
108109

109110
```javascript
110-
var serviceUrl = getenv.url('SERVICE_URL');
111+
const serviceUrl = getenv.url('SERVICE_URL');
111112

112113
serviceUrl.port; // parsed port number
113114
```
@@ -128,7 +129,7 @@ if (process.env.NODE_ENV === 'production') {
128129

129130
```javascript
130131
getenv.disableErrors();
131-
console.log(getenv("RANDOM"));
132+
console.log(getenv('RANDOM'));
132133
// undefined
133134
```
134135

@@ -138,32 +139,48 @@ Revert the effect of `disableErrors()`.
138139

139140
```javascript
140141
getenv.disableErrors();
141-
console.log(getenv("RANDOM"));
142+
console.log(getenv('RANDOM'));
142143
// undefined
143144

144145
getenv.enableErrors();
145-
console.log(getenv("RANDOM"));
146+
console.log(getenv('RANDOM'));
146147
// Error: GetEnv.Nonexistent: RANDOM does not exist and no fallback value provided.
147148
```
148149

149150
## Changelog
150151

152+
### v1.0.0
153+
154+
- Drop support for Node.js older than 6.
155+
- Modernize code.
156+
- Add MIT License in package.json and LICENSE.md.
157+
158+
### v0.7.0
159+
160+
- Add env.disableErrors() / getenv.enableErrors() support.
161+
151162
### v0.6.0
163+
152164
- Added getenv.boolish() support.
153165

154166
### v0.5.0
167+
155168
- Add getenv.url() support.
156169

157170
### v0.4.0
171+
158172
- Add getenv.disableFallbacks() support.
159173

160174
### v0.3.0
175+
161176
- Add getenv.multi() support.
162177

163178
### v0.2.0
179+
164180
- Rename git repository
165181

166182
### v0.1.0
183+
167184
- Initial release
168185

169186
## Authors

index.js

Lines changed: 150 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,150 @@
1-
module.exports = require('./lib/getenv');
1+
const util = require('util');
2+
const url = require('url');
3+
4+
let fallbacksDisabled = false;
5+
let throwError = true;
6+
7+
function _value(varName, fallback) {
8+
const value = process.env[varName];
9+
if (value === undefined) {
10+
if (fallback === undefined && !throwError) {
11+
return value;
12+
}
13+
if (fallback === undefined) {
14+
throw new Error(
15+
'GetEnv.Nonexistent: ' + varName + ' does not exist ' + 'and no fallback value provided.'
16+
);
17+
}
18+
if (fallbacksDisabled) {
19+
throw new Error(
20+
'GetEnv.DisabledFallbacks: ' +
21+
varName +
22+
' relying on fallback ' +
23+
'when fallbacks have been disabled'
24+
);
25+
}
26+
return '' + fallback;
27+
}
28+
return value;
29+
}
30+
31+
const convert = {
32+
string: function(value) {
33+
return '' + value;
34+
},
35+
int: function(value) {
36+
const isInt = value.match(/^-?\d+$/);
37+
if (!isInt) {
38+
throw new Error('GetEnv.NoInteger: ' + value + ' is not an integer.');
39+
}
40+
41+
return +value;
42+
},
43+
float: function(value) {
44+
const isInfinity = +value === Infinity || +value === -Infinity;
45+
if (isInfinity) {
46+
throw new Error('GetEnv.Infinity: ' + value + ' is set to +/-Infinity.');
47+
}
48+
49+
const isFloat = !(isNaN(value) || value === '');
50+
if (!isFloat) {
51+
throw new Error('GetEnv.NoFloat: ' + value + ' is not a number.');
52+
}
53+
54+
return +value;
55+
},
56+
bool: function(value) {
57+
const isBool = value === 'true' || value === 'false';
58+
if (!isBool) {
59+
throw new Error('GetEnv.NoBoolean: ' + value + ' is not a boolean.');
60+
}
61+
62+
return value === 'true';
63+
},
64+
boolish: function(value) {
65+
try {
66+
return convert.bool(value);
67+
} catch (err) {
68+
const isBool = value === '1' || value === '0';
69+
if (!isBool) {
70+
throw new Error('GetEnv.NoBoolean: ' + value + ' is not a boolean.');
71+
}
72+
73+
return value === '1';
74+
}
75+
},
76+
url: url.parse,
77+
};
78+
79+
function converter(type) {
80+
return function(varName, fallback) {
81+
if (typeof varName == 'string') {
82+
// default
83+
const value = _value(varName, fallback);
84+
return convert[type](value);
85+
} else {
86+
// multibert!
87+
return getenv.multi(varName);
88+
}
89+
};
90+
}
91+
92+
const getenv = converter('string');
93+
94+
Object.keys(convert).forEach(function(type) {
95+
getenv[type] = converter(type);
96+
});
97+
98+
getenv.array = function array(varName, type, fallback) {
99+
type = type || 'string';
100+
if (Object.keys(convert).indexOf(type) === -1) {
101+
throw new Error('GetEnv.ArrayUndefinedType: Unknown array type ' + type);
102+
}
103+
const value = _value(varName, fallback);
104+
return value.split(/\s*,\s*/).map(convert[type]);
105+
};
106+
107+
getenv.multi = function multi(spec) {
108+
const result = {};
109+
for (let key in spec) {
110+
const value = spec[key];
111+
if (util.isArray(value)) {
112+
// default value & typecast
113+
switch (value.length) {
114+
case 1: // no default value
115+
case 2: // no type casting
116+
result[key] = getenv(value[0], value[1]); // dirty, when case 1: value[1] is undefined
117+
break;
118+
case 3: // with typecast
119+
result[key] = getenv[value[2]](value[0], value[1]);
120+
break;
121+
default:
122+
// wtf?
123+
throw 'getenv.multi(): invalid spec';
124+
break;
125+
}
126+
} else {
127+
// value or throw
128+
result[key] = getenv(value);
129+
}
130+
}
131+
return result;
132+
};
133+
134+
getenv.disableFallbacks = function() {
135+
fallbacksDisabled = true;
136+
};
137+
138+
getenv.enableFallbacks = function() {
139+
fallbacksDisabled = false;
140+
};
141+
142+
getenv.disableErrors = function() {
143+
throwError = false;
144+
};
145+
146+
getenv.enableErrors = function() {
147+
throwError = true;
148+
};
149+
150+
module.exports = getenv;

0 commit comments

Comments
 (0)