1 | # `patchRequire(vol[, unixifyPaths[, Module]])`
|
---|
2 |
|
---|
3 | Patches Node's `module` module to use a given *fs-like* object `vol` for module loading.
|
---|
4 |
|
---|
5 | - `vol` - fs-like object
|
---|
6 | - `unixifyPaths` *(optional)* - whether to convert Windows paths to unix style paths, defaults to `false`.
|
---|
7 | - `Module` *(optional)* - a module to patch, defaults to `require('module')`
|
---|
8 |
|
---|
9 | Monkey-patches the `require` function in Node, this way you can make
|
---|
10 | Node.js to *require* modules from your custom filesystem.
|
---|
11 |
|
---|
12 | It expects an object with three filesystem methods implemented that are
|
---|
13 | needed for the `require` function to work.
|
---|
14 |
|
---|
15 | ```js
|
---|
16 | let vol = {
|
---|
17 | readFileSync: () => {},
|
---|
18 | realpathSync: () => {},
|
---|
19 | statSync: () => {},
|
---|
20 | };
|
---|
21 | ```
|
---|
22 |
|
---|
23 | If you want to make Node.js to *require* your files from memory, you
|
---|
24 | don't need to implement those functions yourself, just use the
|
---|
25 | [`memfs`](https://github.com/streamich/memfs) package:
|
---|
26 |
|
---|
27 | ```js
|
---|
28 | import {vol} from 'memfs';
|
---|
29 | import {patchRequire} from 'fs-monkey';
|
---|
30 |
|
---|
31 | vol.fromJSON({'/foo/bar.js': 'console.log("obi trice");'});
|
---|
32 | patchRequire(vol);
|
---|
33 | require('/foo/bar'); // obi trice
|
---|
34 | ```
|
---|
35 |
|
---|
36 | Now the `require` function will only load the files from the `vol` file
|
---|
37 | system, but not from the actual filesystem on the disk.
|
---|
38 |
|
---|
39 | If you want the `require` function to load modules from both file
|
---|
40 | systems, use the [`unionfs`](https://github.com/streamich/unionfs) package
|
---|
41 | to combine both filesystems into a union:
|
---|
42 |
|
---|
43 | ```js
|
---|
44 | import {vol} from 'memfs';
|
---|
45 | import {patchRequire} from 'fs-monkey';
|
---|
46 | import {ufs} from 'unionfs';
|
---|
47 | import * as fs from 'fs';
|
---|
48 |
|
---|
49 | vol.fromJSON({'/foo/bar.js': 'console.log("obi trice");'});
|
---|
50 | ufs
|
---|
51 | .use(vol)
|
---|
52 | .use(fs);
|
---|
53 | patchRequire(ufs);
|
---|
54 | require('/foo/bar.js'); // obi trice
|
---|
55 | ```
|
---|