reset-search-paths.js 1.3 KB

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