This repository has been archived by the owner on Nov 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
358 lines (320 loc) · 8.22 KB
/
utils.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
access,
chmod,
close,
copyFile,
mkdir,
open,
readdir,
readFile,
rmdir,
stat,
unlink,
write,
writeFile,
} from 'fs'
import {
basename,
dirname,
join,
normalize,
resolve as pathResolve,
sep,
} from 'path'
import { promisify, TextDecoder, TextEncoder } from 'util'
import {
defer,
from as ofrom,
of,
Observable,
} from 'rxjs'
import {
concatMap,
last,
map,
mapTo,
mergeMap,
scan,
} from 'rxjs/operators'
export const closeAsync = promisify(close)
export const chmodAsync = promisify(chmod)
export const copyFileAsync = promisify(copyFile)
export const mkdirAsync = promisify(mkdir)
export const openAsync = promisify(open)
export const readFileAsync = promisify(readFile)
export const readDirAsync = promisify(readdir)
export const rmdirAsync = promisify(rmdir)
export const statAsync = promisify(stat)
export const unlinkAsync = promisify(unlink)
export const writeAsync = promisify(write)
export const writeFileAsync = promisify(writeFile)
export {
basename,
dirname,
join,
normalize,
pathResolve,
promisify,
}
export { tmpdir } from 'os'
/** Return path if accessible, blank if not accessible */
export function pathAccessible(path: string): Observable<string> {
return defer(() => isPathAccessible(path)).pipe(
map(exists => exists ? normalize(path) : ''),
)
}
// support relative file ('./foo')
export function isPathAccessible(path: string): Promise<boolean> {
return path
? new Promise(resolve => access(path, err => resolve(! err)))
: Promise.resolve(false)
}
/** Check folder path exists, return path if exists, blank if not exists */
export function dirExists(path: string): Observable<string> {
if (! path) {
return of('')
}
const dir = normalize(path)
return defer(() => isDirExists(dir)).pipe(
map(exists => exists ? dir : ''),
)
}
export function isDirExists(path: string): Promise<boolean> {
return path ? isDirFileExists(path, 'DIR') : Promise.resolve(false)
}
/** Check file exists, return path if exists, blank if not exists */
export function fileExists(path: string): Observable<string> {
const file = normalize(path)
return defer(() => isFileExists(file)).pipe(
map(exists => exists ? file : ''),
)
}
export function isFileExists(path: string): Promise<boolean> {
return path ? isDirFileExists(path, 'FILE') : Promise.resolve(false)
}
export function isDirFileExists(path: string, type: 'DIR' | 'FILE'): Promise<boolean> {
if (path) {
return isPathAccessible(path)
.then((accessible) => {
return accessible
? statAsync(path).then((stats) => {
return type === 'DIR' ? stats.isDirectory() : stats.isFile()
})
: false
})
}
else {
return Promise.resolve(false)
}
}
export function createDir(absolutePath: string): Observable<string> {
/* istanbul ignore else */
if (! absolutePath) {
throw new Error('value of path param invalid')
}
// ! normalize required for '.../.myca' under win32
const path$ = of(normalize(absolutePath))
const paths$ = path$.pipe(
mergeMap(target => ofrom(target.split(sep))),
scan((acc: string, curr: string) => pathResolve(acc, curr), sep),
)
const create$ = paths$.pipe(
concatMap(_createDirObb),
last(),
)
const ret$ = path$.pipe(
mergeMap(dirExists),
mergeMap((ps) => {
return ps ? of(ps) : create$
}),
)
return ret$
}
function _createDirObb(path: string): Observable<string> {
return pathAccessible(path).pipe(
mergeMap((str) => {
return str
? of(str)
: defer(() => mkdirAsync(path, 0o755)).pipe(mapTo(path))
}),
)
}
/** create directories recursively */
export async function createDirAsync(path: string): Promise<string> {
if (path) {
const target = normalize(path) // ! required for '.../.myca' under win32
/* istanbul ignore else */
if (! await isDirExists(target)) {
await target.split(sep).reduce(
async (parentDir: Promise<string>, childDir: string) => {
const curDir = pathResolve(await parentDir, childDir)
await isPathAccessible(curDir) || await mkdirAsync(curDir, 0o755)
return curDir
},
Promise.resolve(sep),
)
}
return target
}
else {
throw new Error('value of path param invalid')
}
}
/**
* Create file
* Buffer will be written as binary
* Object will be written as JSON string
*
* @requires string - created file path
*/
export async function createFileAsync(file: string, data: any, options?: WriteFileOptions): Promise<string> {
const dir = dirname(file)
/* istanbul ignore next */
if (! dir) {
throw new Error('folder empty')
}
if (! await isDirExists(dir)) {
await createDirAsync(dir)
}
const path = normalize(file)
/* istanbul ignore else */
if (! await isFileExists(path)) {
const opts: WriteFileOptions = options ? options : { mode: 0o640 }
if (Buffer.isBuffer(data)) {
await writeFileAsync(path, data, opts)
}
else if (typeof data === 'object') {
await writeFileAsync(path, JSON.stringify(data))
}
else {
await writeFileAsync(path, data, opts)
}
}
return path
}
/**
* @deprecated in favor of using child_process['ExecOptions']
*/
export interface ExecFileOptions {
cwd?: string
env?: object
encoding?: 'utf8' | string
timeout?: 0 | number
maxBuffer?: number
killSignal?: string
uid?: number
gid?: number
windowsHide?: boolean
windowsVerbatimArguments?: boolean
}
// param options of fs.writeFile()
export interface WriteFileOptions {
encoding?: string | null
mode?: number
flag?: string
}
/* istanbul ignore next */
/**
* Remove directory recursively
* @see https://stackoverflow.com/a/42505874/3027390
*/
export async function rimraf(path: string): Promise<void> {
if (! path) {
return
}
await _rimraf(path)
if (await isDirExists(path)) {
await rmdirAsync(path)
}
}
/* istanbul ignore next */
async function _rimraf(path: string): Promise<void> {
if (! path) {
return
}
if (await isPathAccessible(path)) {
if (await isFileExists(path)) {
await unlinkAsync(path)
return
}
const entries = await readDirAsync(path)
if (entries.length) {
for (const entry of entries) {
// eslint-disable-next-line no-await-in-loop
await _rimraf(join(path, entry))
}
}
else {
await rmdirAsync(path)
}
}
}
/**
* Validate dll file exists for node-ffi
*/
export async function validateDllFile(path: string): Promise<void> {
if (! path) {
throw new Error('File path empth ')
}
// only filename. can be loaded by search path such as %system%
if (! path.includes('/')) {
return
}
// absolute path
if (await isPathAccessible(path)) {
return
}
throw new Error('File not exists: ' + path)
}
/**
* Convert js ArrayBuffer to Node.js Buffer
*
* @see https://stackoverflow.com/a/14737423
*/
export function ab2buf(ab: ArrayBuffer): Buffer {
return Buffer.from(ab)
}
/**
* Convert Node.js Buffer to js ArrayBuffer
*
* @see https://stackoverflow.com/a/14737423
*/
export function buf2ab(buf: Buffer): ArrayBuffer {
return Uint8Array.from(buf).buffer
}
/**
* Convert ArrayBuffer/TypedArray to String via TextDecoder
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
*/
export function ab2str(
input: ArrayBuffer | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array,
outputEncoding: 'utf8' | 'utf-16' = 'utf8',
): string {
const decoder = new TextDecoder(outputEncoding)
return decoder.decode(input)
}
/**
* Convert String to ArrayBuffer via TextEncoder
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder
*/
export function str2ab(input: string): ArrayBuffer {
const view = str2Uint8Array(input)
return view.buffer
}
/** Convert String to Uint8Array */
export function str2Uint8Array(input: string): Uint8Array {
const encoder = new TextEncoder()
const view = encoder.encode(input)
return view
}
/**
* Generate random integer
*
* @see https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/random
*/
export function genRandomInt(max: number): number {
return Math.floor(Math.random() * Math.floor(max))
}