-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathLocalFilesManager.js
96 lines (84 loc) · 2.31 KB
/
LocalFilesManager.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
import path from 'path';
import autoBind from 'auto-bind';
import debounce from 'lodash/debounce';
/**
* A thin wrapper around Emscripten filesystem.
*/
export default class LocalFilesManager {
constructor(emscriptenFS, rootPath) {
autoBind(this);
this.fs = emscriptenFS;
this.rootPath = rootPath || 'local';
this.fs.mkdirTree(this.rootPath);
this.fs.mount(this.fs.filesystems.IDBFS, {}, this.rootPath);
this.commit = debounce(this.commit, 500);
}
fullPath(filePath) {
// TODO: no-op - the caller of read/write/delete knows about the '/local' root path.
return filePath;
}
/**
* readAll wraps Emscripten FS to make it behave like the
* Chip Player node.js server (browse endpoint).
*/
readAll() {
const fileList = this.fs.readdir(this.rootPath);
if (fileList) {
const filesInfo = fileList
.filter(file => file !== '..' && file !== '.')
.map((file, idx) => {
const fullPath = path.join(this.rootPath, file);
const {
size,
mtime
} = this.fs.stat(fullPath);
return {
idx: idx,
type: 'file',
size: size,
mtime: Math.floor(Date.parse(mtime) / 1000),
path: fullPath,
};
});
// Sort by mtime ascending, then by path ascending
filesInfo.sort((a, b) => {
if (a.mtime !== b.mtime) {
return a.mtime - b.mtime;
} else {
return a.path.localeCompare(b.path);
}
});
return filesInfo;
}
return [];
}
write(filePath, buffer) {
const data = new Uint8Array(buffer)
this.fs.writeFile(this.fullPath(filePath), data);
this.commit();
}
read(filePath) {
return this.fs.readFile(this.fullPath(filePath));
}
delete(filePath) {
if (this.fs.analyzePath(filePath).exists) {
this.fs.unlink(this.fullPath(filePath));
this.commit();
return true;
}
return false;
}
commit() {
return new Promise((resolve, reject) => {
this.fs.syncfs(false, (err) => {
if (err) {
console.error('Error synchronizing local files to indexeddb.', err);
reject();
} else {
console.debug(`Synchronized local files to indexeddb.`);
resolve();
}
});
});
}
}