-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
109 lines (85 loc) · 2.74 KB
/
index.js
File metadata and controls
109 lines (85 loc) · 2.74 KB
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
const fs = require('fs');
const path = require('path');
const LRU = require('lru-cache');
const cache = new LRU({
max: 500,
length: function (n, key) { return n * 2 + key.length },
maxAge: 24 * 60 * 60,
});
const isDir = dir => fs.lstatSync(dir).isDirectory();
const collectPaths = dir => (
fs.readdirSync(dir).reduce((arr, name) => {
const fileDir = path.resolve(dir, name);
isDir(fileDir) ? arr = arr.concat(collectPaths(fileDir)) : arr.push(fileDir);
return arr;
}, [])
);
const collectPathsAsync = dir => {
return fs.promises.readdir(dir).then((res) => {
return res.reduce((arr, name) => {
const fileDir = path.resolve(dir, name);
isDir(fileDir) ? arr = arr.concat(collectPaths(fileDir)) : arr.push(fileDir);
return arr;
}, []);
});
};
const collectFileContent = (rootDir, exts, encoding = 'utf8') => {
if (!Array.isArray(exts)) {
throw new Error(`Arguments types: collectFileContent(String, Array)`);
}
const chacheResult = cache.get('file-content');
if (chacheResult) return chacheResult;
const filePaths = collectPaths(rootDir);
const result = filePaths.reduce((obj, file) => {
if (exts.includes(path.extname(file))) {
const content = fs.readFileSync(file, { encoding });
const ext = path.extname(file).slice(1);
if (!obj[ext]) obj[ext] = [];
obj[ext].push({
name: file.replace(rootDir, ''),
fullName: file,
content,
});
}
return obj;
}, {});
cache.set('file-content', result);
return result;
}
const collectFileContentAsync = (rootDir, exts, encoding = 'utf8') => (
new Promise((resolve, reject) => {
if (!Array.isArray(exts)) {
reject(new Error(`Arguments types: collectFileContent(String, Array)`));
}
const chacheResult = cache.get('file-content');
if (chacheResult) resolve(chacheResult);
collectPathsAsync(rootDir).then((res) => ({
promises: Promise.all(res.map((file) => fs.promises.readFile(file, { encoding }))),
res
})).then(({ promises, res }) => {
resolve(promises.then((contents) => (
res.reduce((obj, file, i) => {
if (exts.includes(path.extname(file))) {
const ext = path.extname(file).slice(1);
if (!obj[ext]) obj[ext] = [];
obj[ext].push({
name: file.replace(rootDir, ''),
fullName: file,
content: contents[i],
});
}
return obj;
}, {})
)))
});
})
);
module.exports = {
collectFileContent: collectFileContent,
collectFilePaths: collectPaths,
};
module.exports.async = {
collectFileContent: collectFileContentAsync,
collectFilePaths: collectPathsAsync,
};
module.exports.isDirectory = isDir;