This repository has been archived by the owner on May 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
229 lines (225 loc) · 6.46 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import * as fs from 'fs'
import * as path from 'path'
/**
* dotenv Manipulator :
* - Load environment variables from a `.env` to `process.env`
* - Add, update, or remove variables from both your `.env` file and `process.env` <b>at runtime</b>
* @example
* ```js
* // require
* const Manipulator = require('dotenv-manipulator').default
* ```
* @example
* ```js
* // import
* import Manipulator from 'dotenv-manipulator'
* ```
*/
class Manipulator {
public env_path: string
public env: { [x: string]: string }
public encoding: 'ascii' | 'base64' | 'binary' | 'hex' | 'latin1' | 'ucs-2' | 'ucs2' | 'utf-8' | 'utf8' | 'utf16le' =
'utf-8'
public throwable: boolean
/**
* Starts dotenv Manipulator
* @param envPath Path to `.env`, default is `process.cwd()`.
* @param throwable If set to `true` functions throw errors whenever there's an incorrect input.
* @param encoding Specify file encoding, default is `utf8`.
* @example
* ```js
* // basic setup
* const Manipulator = require('dotenv-manipulator')
* const dotenvM = new Manipulator()
* ```
* @example
* ```js
* // complete setup
* const Manipulator = require('dotenv-manipulator')
* const dotenvM = new Manipulator('/path/to/project', false, 'utf-8')
* ```
* @example
* ```js
* // undefined = default value
* const Manipulator = require('dotenv-manipulator')
* const dotenvM = new Manipulator(undefined, true, 'latin1')
* ```
*/
constructor(
envPath = path.normalize(process.cwd()),
throwable = false,
encoding:
| 'ascii'
| 'base64'
| 'binary'
| 'hex'
| 'latin1'
| 'ucs-2'
| 'ucs2'
| 'utf-8'
| 'utf8'
| 'utf16le' = 'utf-8'
) {
this.encoding = encoding
this.throwable = throwable
this.env_path = path.join(envPath, '.env')
if (!fs.existsSync(this.env_path)) {
fs.closeSync(fs.openSync(this.env_path, 'w'))
}
this.env = this.__readSync()
this.__sort()
}
private __readSync() {
const OBJ: {
[x: string]: string
} = {}
const file = fs.readFileSync(this.env_path, { encoding: this.encoding }).toString().split(/\r?\n/)
if (file.length) {
for (const line of file) {
if (line !== '') {
const keyvalue = line.split('=')
if (keyvalue.length === 2) {
OBJ[keyvalue[0]] = keyvalue[1]
process.env[keyvalue[0]] = keyvalue[1]
}
}
}
}
return OBJ
}
/**
* Add object keys and values to `.env` file and `process.env`
* @param obj Object to add to the environment
* @param force If you try to add a key/value pair that is already in the environment :<br/>- `add(obj, true)` would update said variables <br/> - `add(obj)` would just ignore your input
* @example
* ```js
* const obj = { REMOTE: '95.81.123.228', PORT: 3000 }
* dotenvM.add(obj)
* ```
* @example
* ```js
* // without force argument
* console.log(process.env.REMOTE_PORT) //=> '3000'
* dotenvM.add({ REMOTE_PORT: '2000' })
* console.log(process.env.REMOTE_PORT) //=> '3000'
*
* // with force argument set to true
* dotenvM.add({ REMOTE_PORT: '2000' }, true)
* console.log(process.env.REMOTE_PORT) //=> '2000'
* ```
* @example
* ```js
* // DEBUGGING #1
* dotenvM.throwable = false
*
* let debug = dotenvM.add(['wrong', 'type', 'of', 'data'])
* let debug_1 = dotenvM.add({ GOOOD: 'type', OF: 'data' })
* console.log(debug.message) //=> [ADD_ERROR]: object must be [object Object] but received [object Array]
* console.log(debug_1) //=> undefined
*
* // DEBUGGING #2
* dotenvM.throwable = true
*
* try {
* dotenvM.add(['wrong', 'type', 'of', 'data'])
* } catch(e) {
* console.log(e.message) //=> [ADD_ERROR]: object must be [object Object] but received [object Array]
* }
* ```
*/
public add(obj: { [x: string]: string }, force = false): TypeError | undefined {
if (Object.prototype.toString.call(obj) !== '[object Object]') {
const errorMessage = new TypeError(
`[ADD_ERROR]: object must be [object Object] but received ${Object.prototype.toString.call(obj)}`
)
if (this.throwable) {
throw errorMessage
} else {
return errorMessage
}
}
for (const res of Object.entries(obj)) {
const key = res[0]
const val = res[1]
if (!this.env[key]) {
this.env[key] = val
process.env[key] = val
} else if (force) {
this.env[key] = val
process.env[key] = val
}
}
this.__save()
}
/**
* Remove variable from `.env` file and `process.env`
* @param obj Key(s) you want to remove
* @example
* ```js
* // #1
* dotenvM.remove('REMOTE')
* dotenvM.remove('PORT')
*
* // #2
* dotenvM.remove( { REMOTE: 'value that dotenvM wont read', PORT: 'no.. really it doesnt care' } )
*
* // #3
* dotenvM.remove(['REMOTE', 'PORT'])
* ```
*/
public remove(obj: { [x: string]: string } | string | string[]): TypeError | undefined {
if (typeof obj === 'string') {
delete process.env[obj]
delete this.env[obj]
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
for (const key of Object.keys(obj)) {
delete process.env[key]
delete this.env[key]
}
} else if (Array.isArray(obj)) {
for (const key of obj) {
delete process.env[key]
delete this.env[key]
}
} else {
const errorMessage = new TypeError(
`[REMOVE_ERROR]: expected [object Object] or [object Array] or [String] but received ${Object.prototype.toString.call(
obj
)}`
)
if (this.throwable) {
throw errorMessage
} else {
return errorMessage
}
}
this.__save()
}
private __sort() {
const order: {
[x: string]: string
} = {}
for (const key of Object.keys(this.env).sort()) {
order[key] = this.env[key]
}
this.env = order
}
private __save() {
this.__sort()
let string = ''
for (const key in this.env) {
if (Object.prototype.hasOwnProperty.call(this.env, key)) {
const val = this.env[key]
string += key + '=' + val + '\n'
}
}
if (string.length) {
fs.writeFileSync(this.env_path, string, { encoding: this.encoding })
} else {
if (Object.keys(this.env).length === 0) {
fs.writeFileSync(this.env_path, string, { encoding: this.encoding })
}
}
}
}
export default Manipulator