-
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
fs-driver-base.js
65 lines (54 loc) · 1.8 KB
/
fs-driver-base.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
const { filename, fileExtension } = require('lib/path-utils');
const { time } = require('lib/time-utils.js');
class FsDriverBase {
async isDirectory(path) {
const stat = await this.stat(path);
return !stat ? false : stat.isDirectory();
}
async readDirStatsHandleRecursion_(basePath, stat, output, options) {
if (options.recursive && stat.isDirectory()) {
const subPath = `${basePath}/${stat.path}`;
const subStats = await this.readDirStats(subPath, options);
for (let j = 0; j < subStats.length; j++) {
const subStat = subStats[j];
subStat.path = `${stat.path}/${subStat.path}`;
output.push(subStat);
}
}
return output;
}
async findUniqueFilename(name) {
let counter = 1;
let nameNoExt = filename(name, true);
let extension = fileExtension(name);
if (extension) extension = `.${extension}`;
let nameToTry = nameNoExt + extension;
while (true) {
const exists = await this.exists(nameToTry);
if (!exists) return nameToTry;
nameToTry = `${nameNoExt} (${counter})${extension}`;
counter++;
if (counter >= 1000) nameToTry = `${nameNoExt} (${new Date().getTime()})${extension}`;
if (counter >= 10000) throw new Error('Cannot find unique title');
}
}
async removeAllThatStartWith(dirPath, filenameStart) {
if (!filenameStart || !dirPath) throw new Error('dirPath and filenameStart cannot be empty');
const stats = await this.readDirStats(dirPath);
for (const stat of stats) {
if (stat.path.indexOf(filenameStart) === 0) {
await this.remove(`${dirPath}/${stat.path}`);
}
}
}
async waitTillExists(path, timeout = 10000) {
const startTime = Date.now();
while (true) {
const e = await this.exists(path);
if (e) return true;
if (Date.now() - startTime > timeout) return false;
await time.msleep(100);
}
}
}
module.exports = FsDriverBase;