Browse Source

Reworks the two functions traverser and findModulePath into a more readable form.

This is not the supposed end of these changes, but a first change that
should make future changes easier to reason about.
v0.7.4-release
Anders Conbere 14 years ago
committed by Ryan Dahl
parent
commit
e9c7195471
  1. 72
      src/node.js

72
src/node.js

@ -146,46 +146,56 @@
removed('require.registerExtension() removed.' + removed('require.registerExtension() removed.' +
' Use require.extensions instead'); ' Use require.extensions instead');
// Which files to traverse while finding id? Returns generator function. // given a module name, and a list of paths to test, returns the first
function traverser(id, dirs) { // matching file in the following precedence.
var head = [], inDir = [], dirs = dirs.slice(), //
// require("a.<ext>")
// -> a.<ext>
//
// require("a")
// -> a
// -> a.<ext>
// -> a/index.<ext>
function findModulePath(request, paths) {
var fs = requireNative('fs'),
exts = Object.keys(extensions); exts = Object.keys(extensions);
return function next() {
var result = head.shift(); paths = request.charAt(0) === '/' ? [''] : paths;
if (result) { return result; }
// check if the file exists and is not a directory
var gen = inDir.shift(); var tryFile = function(requestPath) {
if (gen) { head = gen(); return next(); } try {
stats = fs.statSync(requestPath);
var dir = dirs.shift(); if (stats && !stats.isDirectory()) {
if (dir !== undefined) { return requestPath;
function direct(ext) { return path.join(dir, id + ext); }
function index(ext) { return path.join(dir, id, 'index' + ext); }
inDir = [
function() { return exts.map(direct); },
function() { return exts.map(index); }
];
head = [path.join(dir, id)];
return next();
} }
} catch (e) {}
return false;
}; };
}
function findModulePath(request, paths) { // given a path check a the file exists with any of the set extensions
var nextLoc = var tryExtensions = function(p, extension) {
traverser(request, request.charAt(0) === '/' ? [''] : paths); for (var i = 0, EL = exts.length; i < EL; i++) {
f = tryFile(p + exts[i]);
var fs = requireNative('fs'); if (f) { return f; }
}
return false;
};
var location, stats; // For each path
while (location = nextLoc()) { for (var i = 0, PL = paths.length; i < PL; i++) {
try { stats = fs.statSync(location); } catch (e) { continue; } var p = paths[i],
if (stats && !stats.isDirectory()) return location; // try to join the request to the path
f = tryFile(path.join(p, request)) ||
// try it with each of the extensions
tryExtensions(path.join(p, request)) ||
// try it with each of the extensions at "index"
tryExtensions(path.join(p, request, 'index'));
if (f) { return f; }
} }
return false; return false;
} }
// sync - no i/o performed // sync - no i/o performed
function resolveModuleLookupPaths(request, parent) { function resolveModuleLookupPaths(request, parent) {

Loading…
Cancel
Save