reset-search-paths.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import * as path from 'path';
  2. const Module = require('module');
  3. // Clear Node's global search paths.
  4. Module.globalPaths.length = 0;
  5. // Prevent Node from adding paths outside this app to search paths.
  6. const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep;
  7. const originalNodeModulePaths = Module._nodeModulePaths;
  8. Module._nodeModulePaths = function (from: string) {
  9. const paths: string[] = originalNodeModulePaths(from);
  10. const fromPath = path.resolve(from) + path.sep;
  11. // If "from" is outside the app then we do nothing.
  12. if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
  13. return paths.filter(function (candidate) {
  14. return candidate.startsWith(resourcesPathWithTrailingSlash);
  15. });
  16. } else {
  17. return paths;
  18. }
  19. };
  20. // Make a fake Electron module that we will insert into the module cache
  21. const electronModule = new Module('electron', null);
  22. electronModule.id = 'electron';
  23. electronModule.loaded = true;
  24. electronModule.filename = 'electron';
  25. Object.defineProperty(electronModule, 'exports', {
  26. get: () => require('electron')
  27. });
  28. Module._cache['electron'] = electronModule;
  29. const originalResolveFilename = Module._resolveFilename;
  30. Module._resolveFilename = function (request: string, parent: NodeModule, isMain: boolean) {
  31. if (request === 'electron') {
  32. return 'electron';
  33. } else {
  34. return originalResolveFilename(request, parent, isMain);
  35. }
  36. };