require-at.js 971 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. const Path = require("path");
  3. const Fs = require("fs");
  4. const createRequireFromPath = require("./create-require");
  5. const cache = new Map();
  6. function requireAt(dir, request) {
  7. const makeIt = (xdir, checked) => {
  8. let xRequire = requireAt.cache && requireAt.cache.get(xdir);
  9. if (!xRequire) {
  10. let stat;
  11. try {
  12. stat = Fs.statSync(xdir);
  13. } catch (e) {
  14. throw new Error(`require-at: stat '${xdir}' failed: ${e.message}`);
  15. }
  16. if (!stat || !stat.isDirectory()) {
  17. if (checked) throw new Error(`require-at: not a directory: '${dir}'`);
  18. return makeIt(Path.dirname(xdir), true);
  19. }
  20. xRequire = createRequireFromPath(Path.join(xdir, "._require-at_"), xdir);
  21. requireAt.cache && requireAt.cache.set(xdir, xRequire);
  22. }
  23. return request ? xRequire(request) : xRequire;
  24. };
  25. return makeIt(Path.resolve(dir), false);
  26. }
  27. requireAt.cache = cache;
  28. module.exports = requireAt;