source: trip-planner-front/node_modules/fs-monkey/docs/api/patchRequire.md@ bdd6491

Last change on this file since bdd6491 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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