-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
virtual-fs.js
50 lines (40 loc) · 1.16 KB
/
virtual-fs.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
class VirtualFileSystem {
constructor() {
this.fileData = {};
}
readFileSync(fileName, options = {}) {
const encoding = typeof options === 'string' ? options : options.encoding;
const virtualFileName = normalizeFilename(fileName);
const data = this.fileData[virtualFileName];
if (data == null) {
throw new Error(
`File '${virtualFileName}' not found in virtual file system`
);
}
if (encoding) {
// return a string
return typeof data === 'string' ? data : data.toString(encoding);
}
return Buffer.from(data, typeof data === 'string' ? 'base64' : undefined);
}
writeFileSync(fileName, content) {
this.fileData[normalizeFilename(fileName)] = content;
}
bindFileData(data = {}, options = {}) {
if (options.reset) {
this.fileData = data;
} else {
Object.assign(this.fileData, data);
}
}
}
function normalizeFilename(fileName) {
if (fileName.indexOf(__dirname) === 0) {
fileName = fileName.substring(__dirname.length);
}
if (fileName.indexOf('/') === 0) {
fileName = fileName.substring(1);
}
return fileName;
}
export default new VirtualFileSystem();