-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfsWatcher.js
executable file
·198 lines (179 loc) · 6.13 KB
/
fsWatcher.js
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
let fs;
const getFS = () => fs ? fs : fs = require('fs');
function removeTree(changePath, path, subTree, name) {
const item = subTree[name];
if (name !== '.' && item) {
const type = typeof item;
const nextPath = path + "/" + name;
if (type === 'object') {
item['.']();
for (const itemName in item) {
removeTree(changePath, nextPath, item, itemName);
}
delete subTree[name];
changePath(path, "rd");
} else if (type === 'string') {
delete subTree[name];
changePath(path, "rf");
}
}
}
const fsStat = async (changePath, dirPath, path, files, name, watchers) => {
const subPath = path + "/" + name;
try {
const stats = await fsStats(dirPath + subPath);
if (stats.isDirectory()) {
changePath(subPath, "cd");
const newTree = {};
files[name] = newTree;
await watchDir(changePath, dirPath, subPath, newTree, watchers);
} else if (stats.isFile()) {
changePath(subPath, "cf");
files[name] = stats.ctime.toISOString() + "|" + stats.size;
} else {
throw new Error('Is not a file nor directory');
}
} catch (e) {
removeTree(changePath, subPath, files, name);
}
};
const fsStats = (dirPath) => new Promise((resolve, reject) => {
getFS().stat(dirPath, (err, stats) => err ? reject(err) : resolve(stats));
});
const checkDir = async (dirPath) => {
try {
const stats = await fsStats(dirPath);
return stats.isDirectory();
} catch (e) {
if (e.code === "ENOENT") {
return await mkDir(dirPath);
}
}
};
const mkDir = (dirPath) => new Promise((resolve, reject) => {
getFS().mkdir(dirPath, (err) => {
if (err && err.code === 'ENOENT') {
const parent = dirPath.substr(0, dirPath.lastIndexOf('/'));
if (parent) {
mkDir(parent).then(() => {
mkDir(dirPath).then(resolve).catch(reject);
}).catch(reject);
} else {
reject(err);
}
} else if (err) {
reject(err);
} else {
resolve(true);
}
})
});
const watchDir = async (changePath, dirPath, path = '', files, watchers) => {
const items = await new Promise((resolve, reject) => {
getFS().readdir(dirPath + path, (err, items) => err ? reject(err) : resolve(items));
});
await Promise.all(items.map(name => fsStat(changePath, dirPath, path, files, name, watchers)));
const watcher = getFS().watch(dirPath + path, (eventType, name) =>
fsStat(changePath, dirPath, path, files, name, watchers)
);
watchers.push(watcher);
files['.'] = () => {
const i = watchers.indexOf(watcher);
if (i >= 0) {
watchers.splice(i, 1);
watcher.close();
}
};
files['/'] = () => {
[...watchers].map(watcher => {
const i = watchers.indexOf(watcher);
if (i >= 0) {
watchers.splice(i, 1);
watcher.close();
}
});
}
};
const type = {
'cf': 0,
'rf': 1,
'cd': 2,
'rd': 3
};
const forChangeListener = listener => {
let changes = null;
let changing = null;
function done() {
const arrays = [[], [], [], []];
for (const name in changes) {
arrays[type[changes[name]]].push(name);
}
const [newFiles, removedFiles, newDirectories, removedDirectories] = arrays;
listener({newFiles, removedFiles, newDirectories, removedDirectories});
changing = null;
changes = null;
}
return (path, type) => {
if (!changes) {
changes = {};
}
if (changing !== null) {
clearTimeout(changing);
changing = null;
}
changing = setTimeout(done, 200);
changes[path] = type;
}
};
const watchDirAt = async (dirPath, changeListener) => {
const files = {};
const watchers = [];
if (await checkDir(dirPath)) {
await watchDir(forChangeListener(changeListener), dirPath, '', files, watchers);
}
return files;
};
const fixPath = filePath => {
if (filePath.startsWith("../") || filePath.includes('/../') || filePath.includes('//')) {
throw new Error(`File path '${filePath}' should not include '..' nor '//'`);
}
return !filePath.startsWith('/') ? '/' + filePath : filePath;
};
const filePathReader = dirPath => async filePath => {
fixPath(filePath);
if (!filePath.startsWith('/')) filePath = '/' + filePath;
return await new Promise((resolve, reject) =>
getFS().readFile(dirPath + filePath, (e, data) => e ? reject(e) : resolve(data))
)
};
const mkdir = async (dirPath, parent) => {
const index = parent.lastIndexOf('/');
if (index > 0) {
await mkdir(dirPath, parent.substr(0, index));
}
const stat = await new Promise(resolve =>
getFS().stat(dirPath + parent, (err, stat) => err ? resolve(null) : resolve(stat))
);
if (!stat || !stat.isDirectory()) {
await new Promise((resolve, reject) =>
getFS().mkdir(dirPath + parent, {recursive: true}, e => e ? reject(e) : resolve())
);
}
};
const filePathWriter = dirPath => async (filePath, data, options) => {
filePath = fixPath(filePath);
if (!data) {
await new Promise((resolve, reject) =>
getFS().unlink(dirPath + filePath, e => e ? reject(e) : resolve())
);
return
}
await mkdir(dirPath, filePath.substr(0, filePath.lastIndexOf('/')));
await saveFile(dirPath + filePath, data, options);
};
const getFile = async name => await new Promise(resolve => getFS().readFile(name, (err, data) => resolve(data)));
const readFile = async name => await getFile(name.replace('~/', __dirname+"/"));
const saveFile = async (name, data, options) => await new Promise((resolve, reject) =>
getFS().writeFile(name, data, options, e => e ? reject(e) : resolve())
);
module.exports = {watchDirAt, filePathReader, filePathWriter, getFile, readFile, saveFile, getFS};