1 | "use strict";
|
2 |
|
3 | exports.__esModule = true;
|
4 | exports.default = proxyFileSystem;
|
5 |
|
6 | const uniq = require('lodash/uniq');
|
7 |
|
8 | const withSyncMethod = (methods, name) => [...methods, name, `${name}Sync`];
|
9 |
|
10 | const TO_PROXY = ['exists', 'readFile', 'writeFile', 'stat', 'unlink'].reduce(withSyncMethod, []).concat(['createReadStream', 'createWriteStream']);
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | function proxyFileSystem(realFs, virtualFs) {
|
17 | const proto = Object.getPrototypeOf(realFs);
|
18 | const fs = Object.create(proto);
|
19 | const proxiedMethods = {
|
20 | __isProxiedFileSystem: true
|
21 | };
|
22 | TO_PROXY.forEach(method => {
|
23 |
|
24 | if (typeof realFs[method] !== 'function') return;
|
25 |
|
26 | proxiedMethods[method] = function proxy(path, ...args) {
|
27 | if (!virtualFs.existsSync(path)) {
|
28 | return realFs[method](path, ...args);
|
29 | }
|
30 |
|
31 | if (!virtualFs[method]) {
|
32 | const err = new Error(`[VirtualModulePlugin] unsupport method: \`${method}\`` + ` on virtual file: \`${path}\`.`);
|
33 | if (method.endsWith('Sync')) throw err;else return args.pop()(err);
|
34 | }
|
35 |
|
36 | return virtualFs[method](path, ...args);
|
37 | };
|
38 | });
|
39 |
|
40 | proxiedMethods.readdirSync = function readdirSync(dirPath) {
|
41 | const virtualFiles = virtualFs.existsSync(dirPath) ? virtualFs.readdirSync(dirPath) : [];
|
42 | return uniq([...realFs.readdirSync(dirPath), ...virtualFiles]);
|
43 | };
|
44 |
|
45 | proxiedMethods.readdir = function readdir(dirPath, cb) {
|
46 | realFs.readdir(dirPath, (err, realFiles) => {
|
47 | if (err) return cb(err);
|
48 | const virtualFiles = virtualFs.existsSync(dirPath) ? virtualFs.readdirSync(dirPath) : [];
|
49 | return cb(null, uniq([...realFiles, ...virtualFiles]));
|
50 | });
|
51 | };
|
52 |
|
53 | return Object.assign(fs, realFs, proxiedMethods);
|
54 | } |
\ | No newline at end of file |