You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.6 KiB

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