跳到主要内容

Module._resolveLookupPaths 源码解析

Module._resolveLookupPaths = function (request, parent) {
if (NativeModule.canBeRequiredByUsers(request)) {
debug("looking for %j in []", request);
return null;
}

// Check for node modules paths.
if (
StringPrototypeCharAt(request, 0) !== "." ||
(request.length > 1 &&
StringPrototypeCharAt(request, 1) !== "." &&
StringPrototypeCharAt(request, 1) !== "/" &&
(!isWindows || StringPrototypeCharAt(request, 1) !== "\\"))
) {
let paths = modulePaths;
if (parent != null && parent.paths && parent.paths.length) {
paths = ArrayPrototypeConcat(parent.paths, paths);
}

debug("looking for %j in %j", request, paths);
return paths.length > 0 ? paths : null;
}

// In REPL, parent.filename is null.
if (!parent || !parent.id || !parent.filename) {
// Make require('./path/to/foo') work - normally the path is taken
// from realpath(__filename) but in REPL there is no filename
const mainPaths = ["."];

debug("looking for %j in %j", request, mainPaths);
return mainPaths;
}

debug("RELATIVE: requested: %s from parent.id %s", request, parent.id);

const parentDir = [path.dirname(parent.filename)];
debug("looking for %j", parentDir);
return parentDir;
};

1. 判断是否为内置模块

if (NativeModule.canBeRequiredByUsers(request)) {
debug("looking for %j in []", request);
return null;
}

如果是内置模块,返回 null

2. 判断 request 的值

// Check for node modules paths.
if (
request.charAt(0) !== "." ||
(request.length > 1 &&
StringPrototypeCharAt(request, 1) !== "." &&
StringPrototypeCharAt(request, 1) !== "/" &&
(!isWindows || StringPrototypeCharAt(request, 1) !== "\\"))
) {
let paths = modulePaths;
if (parent != null && parent.paths && parent.paths.length) {
paths = ArrayPrototypeConcat(parent.paths, paths);
}

debug("looking for %j in %j", request, paths);
return paths.length > 0 ? paths : null;
}
  • request 是否为相对路径
    • request 是一个 .
    • request 是以 . 开头的
    • request 是以 / 开头的

2.1 获取模块目录

let paths = modulePaths;

modulePaths 是在环境变量中存储的一些环境变量的目录

2.2 添加路径

if (parent != null && parent.paths && parent.paths.length) {
paths = parent.paths.concat(paths);
}

合并到传递过来的数组中