Filter existing search paths instead reimplementing
authorKevin Sawicki <kevinsawicki@gmail.com>
Thu, 23 Jun 2016 22:27:45 +0000 (15:27 -0700)
committerKevin Sawicki <kevinsawicki@gmail.com>
Thu, 23 Jun 2016 22:27:45 +0000 (15:27 -0700)
lib/common/reset-search-paths.js
spec/modules-spec.js

index 4d09f6c..8e21701 100644 (file)
@@ -9,30 +9,19 @@ module.paths = []
 module.parent.paths = []
 
 // Prevent Node from adding paths outside this app to search paths.
+const originalNodeModulePaths = Module._nodeModulePaths
 Module._nodeModulePaths = function (from) {
-  from = path.resolve(from)
+  const paths = originalNodeModulePaths(from)
+  const rootPath = process.resourcesPath
 
   // If "from" is outside the app then we do nothing.
-  const skipOutsidePaths = from.startsWith(process.resourcesPath)
-
-  // Following logic is copied from module.js.
-  const splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//
-  const paths = []
-  const parts = from.split(splitRe)
-
-  let tip
-  let i
-  for (tip = i = parts.length - 1; i >= 0; tip = i += -1) {
-    const part = parts[tip]
-    if (part === 'node_modules') {
-      continue
-    }
-    const dir = parts.slice(0, tip + 1).join(path.sep)
-    if (skipOutsidePaths && !dir.startsWith(process.resourcesPath)) {
-      break
-    }
-    paths.push(path.join(dir, 'node_modules'))
+  const skipOutsidePaths = path.resolve(from).startsWith(rootPath)
+  if (skipOutsidePaths) {
+    return paths.filter(function (candidate) {
+      return candidate.startsWith(rootPath)
+    })
   }
+
   return paths
 }
 
index c3ad4bc..87396ac 100644 (file)
@@ -89,8 +89,7 @@ describe('Module._nodeModulePaths', function () {
     it('includes paths outside of the resources path', function () {
       let modulePath = path.resolve('/foo')
       assert.deepEqual(Module._nodeModulePaths(modulePath), [
-        path.join(modulePath, 'node_modules'),
-        path.join('node_modules')
+        path.join(modulePath, 'node_modules')
       ])
     })
   })