-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
58 lines (45 loc) · 1.31 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
import {readFile, readdir, writeFile, statSync} from 'fs'
import {resolve, join} from 'path'
const log = (err: Error) => console.log(err);
const isFile = (f: string) => statSync(f).isFile();
const write = (fName: string, str: string) => new Promise((res, rej) => {
writeFile(resolve(fName), str, (err: Error) => {
if (err) return rej(err)
return res(str)
})
});
const readFolder = (folder: string) => new Promise((res, rej) => {
readdir(resolve(folder), (err, files) => {
if (err) rej(err)
const fileList = files.map(f => join(folder, f));
res(fileList.filter(isFile));
})
});
const read = (fName: string) => new Promise((res, rej) => {
readFile(resolve(fName), (err, str) => {
if (err) rej(err)
res(str)
})
});
const concat = (files: string[]) => new Promise((res, rej) => {
return Promise.all(files.map(read))
.then(src => res(src.join('\n')))
.catch(rej);
});
export = (folder: string[] | string, outFile?: string) => new Promise((res, rej) => {
let concatenated;
if(typeof folder === 'string') {
concatenated = readFolder(folder)
.then(concat);
} else {
concatenated = concat(folder);
}
if (outFile) {
concatenated.then((out: string) => write(outFile, out)
.then(res)
.catch(rej)
).catch(rej);
} else {
concatenated.then(res).catch(rej);
}
});