-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathfs-virtual.cjs
104 lines (88 loc) · 2.71 KB
/
fs-virtual.cjs
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
// @ts-check
"use strict";
const dirent = (path, directory) => {
const name = path.replace(/^.*\//u, "");
return {
name,
"isBlockDevice": () => false,
"isCharacterDevice": () => false,
"isDirectory": directory ? () => true : () => false,
"isFIFO": () => false,
"isFile": directory ? () => false : () => true,
"isSocket": () => false,
"isSymbolicLink": () => false
};
};
const normalize = (path) => path.replace(/^[A-Za-z]:/u, "").replaceAll("\\", "/");
/* eslint-disable no-param-reassign */
class FsVirtual {
constructor(files) {
this.files = new Map(files);
this.promises = {};
this.promises.access = (path) => {
path = normalize(path);
if (this.files.has(path)) {
return Promise.resolve();
}
return Promise.reject(new Error(`fs-virtual:promises.access(${path})`));
};
this.promises.readFile = (path) => {
path = normalize(path);
const content = this.files.get(path);
if (content) {
return Promise.resolve(content);
}
return Promise.reject(new Error(`fs-virtual:promises.readFile(${path})`));
};
this.promises.stat = (path) => {
path = normalize(path);
if (this.files.has(path)) {
return Promise.resolve(dirent(path));
}
return Promise.reject(new Error(`fs-virtual:promises.stat(${path})`));
};
this.promises.writeFile = (path, data) => {
path = normalize(path);
this.files.set(path, data);
};
this.access = (path, mode, callback) => {
path = normalize(path);
if (this.files.has(path)) {
return (callback || mode)();
}
return (callback || mode)(new Error(`fs-virtual:access(${path})`));
};
// eslint-disable-next-line no-multi-assign
this.stat = this.lstat = (path, callback) => {
path = normalize(path);
if (this.files.has(path)) {
return callback(null, dirent(path, false));
}
return callback(null, dirent(path, true));
};
this.readdir = (path, options, callback) => {
path = normalize(path);
const names = [];
for (const file of this.files.keys()) {
if (file.startsWith(`${path}`)) {
const [ name ] = file.slice(path.length).split("/");
if (!names.includes(name)) {
names.push(name);
}
}
}
return (callback || options)(null, names);
};
this.readFile = (path, options, callback) => {
path = normalize(path);
const content = this.files.get(path);
if (content) {
return callback(null, content);
}
return callback(new Error(`fs-virtual:readFile(${path})`));
};
}
}
if (typeof module !== "undefined") {
module.exports = FsVirtual;
}