reset-search-paths.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict'
  2. const path = require('path')
  3. const Module = require('module')
  4. // Clear Node's global search paths.
  5. Module.globalPaths.length = 0
  6. // Clear current and parent(init.js)'s search paths.
  7. module.paths = []
  8. module.parent.paths = []
  9. // Prevent Node from adding paths outside this app to search paths.
  10. const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep
  11. const originalNodeModulePaths = Module._nodeModulePaths
  12. Module._nodeModulePaths = function (from) {
  13. const paths = originalNodeModulePaths(from)
  14. const fromPath = path.resolve(from) + path.sep
  15. // If "from" is outside the app then we do nothing.
  16. if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
  17. return paths.filter(function (candidate) {
  18. return candidate.startsWith(resourcesPathWithTrailingSlash)
  19. })
  20. } else {
  21. return paths
  22. }
  23. }
  24. const BASE_INTERNAL_PATH = path.resolve(__dirname, '..')
  25. const INTERNAL_MODULE_PREFIX = '@electron/internal/'
  26. // Patch Module._resolveFilename to always require the Electron API when
  27. // require('electron') is done.
  28. const electronPath = path.join(__dirname, '..', process.type, 'api', 'exports', 'electron.js')
  29. const originalResolveFilename = Module._resolveFilename
  30. Module._resolveFilename = function (request, parent, isMain) {
  31. if (request === 'electron') {
  32. return electronPath
  33. } else if (request.startsWith(INTERNAL_MODULE_PREFIX) && request.length > INTERNAL_MODULE_PREFIX.length) {
  34. const slicedRequest = request.slice(INTERNAL_MODULE_PREFIX.length)
  35. return path.resolve(BASE_INTERNAL_PATH, `${slicedRequest}${slicedRequest.endsWith('.js') ? '' : '.js'}`)
  36. } else {
  37. return originalResolveFilename(request, parent, isMain)
  38. }
  39. }