electron/lib/common/reset-search-paths.js

50 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-03-25 19:57:17 +00:00
const path = require('path')
const Module = require('module')
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Clear Node's global search paths.
2016-03-25 19:57:17 +00:00
Module.globalPaths.length = 0
2016-01-12 02:40:23 +00:00
2016-05-23 17:28:32 +00:00
// Clear current and parent(init.js)'s search paths.
2016-03-25 19:57:17 +00:00
module.paths = []
module.parent.paths = []
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Prevent Node from adding paths outside this app to search paths.
2016-03-25 19:57:17 +00:00
Module._nodeModulePaths = function (from) {
from = path.resolve(from)
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// If "from" is outside the app then we do nothing.
2016-05-23 17:58:33 +00:00
const skipOutsidePaths = from.startsWith(process.resourcesPath)
2016-01-12 02:40:23 +00:00
2016-05-23 17:56:49 +00:00
// Following logic is copied from module.js.
2016-05-23 17:58:33 +00:00
const splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//
const paths = []
const parts = from.split(splitRe)
2016-05-23 18:31:56 +00:00
let tip
let i
for (tip = i = parts.length - 1; i >= 0; tip = i += -1) {
2016-05-23 17:58:33 +00:00
const part = parts[tip]
2016-01-12 02:40:23 +00:00
if (part === 'node_modules') {
2016-03-25 19:57:17 +00:00
continue
2016-01-12 02:40:23 +00:00
}
2016-05-23 17:58:33 +00:00
const dir = parts.slice(0, tip + 1).join(path.sep)
2016-01-12 02:40:23 +00:00
if (skipOutsidePaths && !dir.startsWith(process.resourcesPath)) {
2016-03-25 19:57:17 +00:00
break
2016-01-12 02:40:23 +00:00
}
2016-03-25 19:57:17 +00:00
paths.push(path.join(dir, 'node_modules'))
2016-01-12 02:40:23 +00:00
}
2016-03-25 19:57:17 +00:00
return paths
}
2016-05-23 17:56:49 +00:00
2016-05-23 22:15:39 +00:00
// Patch Module._resolveFilename to always require the Electron API when
// require('electron') is done.
2016-05-23 17:56:49 +00:00
const electronPath = path.join(__dirname, '..', process.type, 'api', 'exports', 'electron.js')
const originalResolveFilename = Module._resolveFilename
Module._resolveFilename = function (request, parent, isMain) {
if (request === 'electron') {
return electronPath
} else {
return originalResolveFilename(request, parent, isMain)
}
}