Skip to content

Commit d2816d8

Browse files
keithamusljharb
authored andcommitted
[Performance] use isDirectory to speed up node_modules lookups
This is a backport of 4cf8928 and fa11d48 (#190 and #191) to the 1.x branch. This offers a small but useful performance improvement by avoiding unnecessary stat calls.
1 parent b502f7c commit d2816d8

File tree

4 files changed

+17
-6
lines changed

4 files changed

+17
-6
lines changed

lib/async.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -219,8 +219,14 @@ module.exports = function resolve(x, options, callback) {
219219
if (dirs.length === 0) return cb(null, undefined);
220220
var dir = dirs[0];
221221

222-
var file = path.join(dir, x);
223-
loadAsFile(file, opts.package, onfile);
222+
isDirectory(dir, isdir);
223+
224+
function isdir(err, isdir) {
225+
if (err) return cb(err);
226+
if (!isdir) return processDirs(cb, dirs.slice(1));
227+
var file = path.join(dir, x);
228+
loadAsFile(file, opts.package, onfile);
229+
}
224230

225231
function onfile(err, m, pkg) {
226232
if (err) return cb(err);

lib/sync.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,10 +156,12 @@ module.exports = function (x, options) {
156156
var dirs = nodeModulesPaths(start, opts, x);
157157
for (var i = 0; i < dirs.length; i++) {
158158
var dir = dirs[i];
159-
var m = loadAsFileSync(path.join(dir, '/', x));
160-
if (m) return m;
161-
var n = loadAsDirectorySync(path.join(dir, '/', x));
162-
if (n) return n;
159+
if (isDirectory(dir)) {
160+
var m = loadAsFileSync(path.join(dir, '/', x));
161+
if (m) return m;
162+
var n = loadAsDirectorySync(path.join(dir, '/', x));
163+
if (n) return n;
164+
}
163165
}
164166
}
165167
};

test/mock.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ test('mock package', function (t) {
108108

109109
var dirs = {};
110110
dirs[path.resolve('/foo')] = true;
111+
dirs[path.resolve('/foo/node_modules')] = true;
111112

112113
function opts(basedir) {
113114
return {
@@ -142,6 +143,7 @@ test('mock package from package', function (t) {
142143

143144
var dirs = {};
144145
dirs[path.resolve('/foo')] = true;
146+
dirs[path.resolve('/foo/node_modules')] = true;
145147

146148
function opts(basedir) {
147149
return {

test/mock_sync.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ test('mock package', function (t) {
5656

5757
var dirs = {};
5858
dirs[path.resolve('/foo')] = true;
59+
dirs[path.resolve('/foo/node_modules')] = true;
5960

6061
function opts(basedir) {
6162
return {

0 commit comments

Comments
 (0)