UNPKG

1.35 kBJavaScriptView Raw
1'use strict';
2
3class VirtualFileSystem {
4 constructor() {
5 this.fileData = {};
6 }
7 readFileSync(fileName, options) {
8 if (options === void 0) {
9 options = {};
10 }
11 const encoding = typeof options === 'string' ? options : options.encoding;
12 const virtualFileName = normalizeFilename(fileName);
13 const data = this.fileData[virtualFileName];
14 if (data == null) {
15 throw new Error(`File '${virtualFileName}' not found in virtual file system`);
16 }
17 if (encoding) {
18 // return a string
19 return typeof data === 'string' ? data : data.toString(encoding);
20 }
21 return Buffer.from(data, typeof data === 'string' ? 'base64' : undefined);
22 }
23 writeFileSync(fileName, content) {
24 this.fileData[normalizeFilename(fileName)] = content;
25 }
26 bindFileData(data, options) {
27 if (data === void 0) {
28 data = {};
29 }
30 if (options === void 0) {
31 options = {};
32 }
33 if (options.reset) {
34 this.fileData = data;
35 } else {
36 Object.assign(this.fileData, data);
37 }
38 }
39}
40function normalizeFilename(fileName) {
41 if (fileName.indexOf(__dirname) === 0) {
42 fileName = fileName.substring(__dirname.length);
43 }
44 if (fileName.indexOf('/') === 0) {
45 fileName = fileName.substring(1);
46 }
47 return fileName;
48}
49var virtualFs = new VirtualFileSystem();
50
51module.exports = virtualFs;