Skip to content

Commit 747869f

Browse files
committed
Add limitStat to keep concurrent requests under control
1 parent d01534f commit 747869f

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

lib/view.js

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ function resolveView(dir, file, ext, cb) {
215215
var path = join(dir, file);
216216

217217
// <path>.<ext>
218-
fs.stat(path, function (err, stat) {
218+
limitStat(path, function (err, stat) {
219219
if (err && err.code != 'ENOENT') {
220220
return cb(err);
221221
} else if (!err && stat && stat.isFile()) {
@@ -224,7 +224,7 @@ function resolveView(dir, file, ext, cb) {
224224

225225
// <path>/index.<ext>
226226
path = join(dir, basename(file, ext), 'index' + ext);
227-
fs.stat(path, function (err, stat) {
227+
limitStat(path, function (err, stat) {
228228
if (err && err.code == 'ENOENT') {
229229
return cb(null, null);
230230
} else if (!err && stat && stat.isFile()) {
@@ -235,3 +235,31 @@ function resolveView(dir, file, ext, cb) {
235235
});
236236
});
237237
}
238+
239+
var pendingStats = [];
240+
var numPendingStats = 0;
241+
/**
242+
* an fs.stat call that limits the number of outstanding requests to 10.
243+
*
244+
* @param {String} path
245+
* @param {Function} cb
246+
*/
247+
function limitStat(path, cb) {
248+
if (++numPendingStats > 10) {
249+
pendingStats.push([path, cb]);
250+
} else {
251+
fs.stat(path, cbAndDequeue(cb));
252+
}
253+
254+
function cbAndDequeue(cb) {
255+
return function (err, stat) {
256+
cb(err, stat);
257+
var next = pendingStats.shift();
258+
if (next) {
259+
fs.stat(next[0], cbAndDequeue(next[1]));
260+
} else {
261+
numPendingStats--;
262+
}
263+
}
264+
}
265+
}

0 commit comments

Comments
 (0)