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.

47 lines
1.1 KiB

4 years ago
  1. 'use strict';
  2. const path = require('path');
  3. const Module = require('module');
  4. const fs = require('fs');
  5. const resolveFrom = (fromDir, moduleId, silent) => {
  6. if (typeof fromDir !== 'string') {
  7. throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDir}\``);
  8. }
  9. if (typeof moduleId !== 'string') {
  10. throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``);
  11. }
  12. try {
  13. fromDir = fs.realpathSync(fromDir);
  14. } catch (err) {
  15. if (err.code === 'ENOENT') {
  16. fromDir = path.resolve(fromDir);
  17. } else if (silent) {
  18. return null;
  19. } else {
  20. throw err;
  21. }
  22. }
  23. const fromFile = path.join(fromDir, 'noop.js');
  24. const resolveFileName = () => Module._resolveFilename(moduleId, {
  25. id: fromFile,
  26. filename: fromFile,
  27. paths: Module._nodeModulePaths(fromDir)
  28. });
  29. if (silent) {
  30. try {
  31. return resolveFileName();
  32. } catch (err) {
  33. return null;
  34. }
  35. }
  36. return resolveFileName();
  37. };
  38. module.exports = (fromDir, moduleId) => resolveFrom(fromDir, moduleId);
  39. module.exports.silent = (fromDir, moduleId) => resolveFrom(fromDir, moduleId, true);