Check if module path is already loaded before doing fs operations

resolve now checks the existence of a module already loaded at the
given path before checking if the file exists on disk.

This removes the need for many redundant fs.exists and fs.isFile
calls for already loaded modules.

This speeds up package loading since most packages have a common
set of requires that were doing needless fs operations for each
searched path when the module was already in the cache at that
path.
This commit is contained in:
Kevin Sawicki
2013-01-18 08:50:07 -08:00
parent 9067f1fbb9
commit f29c3a0836

View File

@@ -73,16 +73,25 @@ resolve = (name, {verifyExistence}={}) ->
file = file.replace '../', "#{prefix}/"
if file[0] isnt '/'
paths.some (path) ->
fileExists = /\.(.+)$/.test(file) and __exists "#{path}/#{file}"
jsFileExists = not /\.(.+)$/.test(file) and __exists "#{path}/#{file}.js"
if jsFileExists
file = "#{path}/#{file}.js"
else if fileExists
moduleAlreadyLoaded = paths.some (path) ->
if __moduleExists "#{path}/#{file}"
file = "#{path}/#{file}"
else if expanded = __expand "#{path}/#{file}"
else if __moduleExists "#{path}/#{file}.js"
file = "#{path}/#{file}.js"
else if expanded = __moduleExpand "#{path}/#{file}"
file = expanded
if not moduleAlreadyLoaded
paths.some (path) ->
fileExists = /\.(.+)$/.test(file) and __exists "#{path}/#{file}"
jsFileExists = not /\.(.+)$/.test(file) and __exists "#{path}/#{file}.js"
if jsFileExists
file = "#{path}/#{file}.js"
else if fileExists
file = "#{path}/#{file}"
else if expanded = __expand "#{path}/#{file}"
file = expanded
else
file = __expand(file) or file
@@ -92,16 +101,27 @@ resolve = (name, {verifyExistence}={}) ->
console.warn("Failed to resolve '#{name}'") if verifyExistence
null
__moduleExists = (path) ->
__modules[path] isnt undefined
__moduleExpand = (path) ->
return path if __moduleExists path
for ext, handler of exts
return "#{path}.#{ext}" if __moduleExists "#{path}.#{ext}"
return "#{path}/index.#{ext}" if __moduleExists "#{path}/index.#{ext}"
null
__expand = (path) ->
modulePath = __moduleExpand path
return modulePath if modulePath
return path if __isFile path
for ext, handler of exts
if __exists "#{path}.#{ext}"
return "#{path}.#{ext}"
else if __exists "#{path}/index.#{ext}"
return "#{path}/index.#{ext}"
return "#{path}.#{ext}" if __exists "#{path}.#{ext}"
return "#{path}/index.#{ext}" if __exists "#{path}/index.#{ext}"
return path if __exists path
return null
null
__exists = (path) ->
$native.exists path