Skip to content

Commit

Permalink
module: define functions only once.
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs authored and ry committed Feb 3, 2011
1 parent 8ee9c53 commit 2f1f22a
Showing 1 changed file with 34 additions and 25 deletions.
59 changes: 34 additions & 25 deletions lib/module.js
Expand Up @@ -51,6 +51,38 @@ var debug = Module._debug;
// -> a
// -> a.<ext>
// -> a/index.<ext>

function statPath(path) {
var fs = NativeModule.require('fs');
try {
return fs.statSync(path);
} catch (ex) {}
return false;
}

// check if the file exists and is not a directory
function tryFile(requestPath) {
var fs = NativeModule.require('fs');
var stats = statPath(requestPath);
if (stats && !stats.isDirectory()) {
return fs.realpathSync(requestPath);
}
return false;
}

// given a path check a the file exists with any of the set extensions
function tryExtensions(p, exts) {
for (var i = 0, EL = exts.length; i < EL; i++) {
var filename = tryFile(p + exts[i]);

if (filename) {
return filename;
}
}
return false;
}


Module._findPath = function(request, paths) {
var fs = NativeModule.require('fs');
var exts = Object.keys(Module._extensions);
Expand All @@ -61,29 +93,6 @@ Module._findPath = function(request, paths) {

var trailingSlash = (request.slice(-1) === '/');

// check if the file exists and is not a directory
function tryFile(requestPath) {
try {
var stats = fs.statSync(requestPath);
if (stats && !stats.isDirectory()) {
return fs.realpathSync(requestPath);
}
} catch (e) {}
return false;
};

// given a path check a the file exists with any of the set extensions
function tryExtensions(p, extension) {
for (var i = 0, EL = exts.length; i < EL; i++) {
var filename = tryFile(p + exts[i]);

if (filename) {
return filename;
}
}
return false;
};

var cacheKey = JSON.stringify({request: request, paths: paths});
if (Module._pathCache[cacheKey]) {
return Module._pathCache[cacheKey];
Expand All @@ -100,13 +109,13 @@ Module._findPath = function(request, paths) {

if (!filename && !trailingSlash) {
// try it with each of the extensions
filename = tryExtensions(basePath);
filename = tryExtensions(basePath, exts);
}
}

if (!filename) {
// try it with each of the extensions at "index"
filename = tryExtensions(path.resolve(basePath, 'index'));
filename = tryExtensions(path.resolve(basePath, 'index'), exts);
}

if (filename) {
Expand Down

0 comments on commit 2f1f22a

Please sign in to comment.