UNPKG

1.82 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.default = proxyFileSystem;
5
6const uniq = require('lodash/uniq');
7
8const withSyncMethod = (methods, name) => [...methods, name, `${name}Sync`];
9
10const TO_PROXY = ['exists', 'readFile', 'writeFile', 'stat', 'unlink'].reduce(withSyncMethod, []).concat(['createReadStream', 'createWriteStream']);
11/**
12 * Wrap the filesystem object so that fs actions on virtual files
13 * are handled correctly
14 */
15
16function 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 // only proxy methods present in the real fs
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