蓝色天空.知识 · 实践 · 创造
我的收藏
Node.js 教程目录 38章
Node.js / LEARN BY DOING

Node.js 模块系统

核对 Node.js 模块分类(内置/自定义/第三方)、CommonJS exports 与 module.exports 引用差异、ES 模块语法、模块缓存与刷新、循环依赖、函数包装作用域及 require 路径解析算法。

学完这一章,你能够

  • 核对 Node.js 模块分类(内置/自定义/第三方)、CommonJS exports 与 module.exports 引用差异、ES 模块语法、模块缓存与刷新、循环依赖、函数包装作用域及 require 路径解析算法。

模块概念、三类模块与导入方式

Node.js 将每个独立的 JavaScript 文件视作拥有私有作用域的模块,借此将复杂应用拆分为可复用、易维护的功能单元。系统同时支持传统 CommonJS 与现代 ES 模块,按来源分为内置模块(如 `fs`、`http`、`path`、`os`、`crypto`)、用户自定义模块与通过 npm 安装的第三方模块(如 `express`、`lodash`、`axios`)。

内置模块随 Node.js 一同分发无需安装,调用 `require('os')`(现代更推荐显式 `node:os` 前缀避免与同名依赖冲突)即可读取系统平台与内存;第三方模块经 `npm install <pkg>` 写入项目的 `node_modules` 目录后,同样按包名直接 `require()` 加载。

自定义 CommonJS 模块与 exports/module.exports 差异

CommonJS 中通过 `exports` 或 `module.exports` 暴露接口、以 `require('./hello')` 加载同目录模块(默认可省略 `.js` 扩展名)。当需要向模块对象挂载多个属性或方法时,可直接写 `exports.world = function() { ... }`,外部加载后调用 `hello.world()`(本站实测返回 `'Hello World'`)。

若希望模块直接导出单个构造函数、类或对象本身,则应赋值给 `module.exports = Hello`(实测实例化后返回 `'Hello NodeUser'`)。务必牢记:`module.exports` 才是模块真正的导出对象引用,`exports` 仅是指向它的初始快捷变量;若直接重赋值 `exports = { secret: 42 }` 会断开引用,外部最终拿到的仍是空对象 `{}`(本站实测 `brokenReassignKeys` 为 `[]`)。简言之,零散挂载属性方法可用 `exports`,整体导出类或单值用 `module.exports`。

ES 模块语法与路径分类

ES 模块采用 `import` 与 `export` 关键字,通过 `.mjs` 扩展名或在 `package.json` 设置 `"type": "module"` 启用,既支持编译期静态导入 `import ... from ...` 也支持返回 Promise 的动态 `import()`(本站动态导入临时 `.mjs` 模块调用 `greet('Bob')` 返回 `'Hello, Bob!'`)。模块路径分为核心模块(直接写名)、本地文件模块(以 `./`、`../` 或 `/` 开头)与位于 `node_modules` 的第三方模块(直接写包名)。

模块缓存、循环依赖与函数包装作用域

Node.js 会把已加载的 CommonJS 模块缓存在 `require.cache` 中,重复 `require()` 同一路径直接命中缓存而不重新执行文件;如需强制重载可先执行 `delete require.cache[require.resolve('./mod')]`。本站实测两次加载计数器模块返回同一引用(`sameRef: true`、`loadSeq: 1`),删除缓存后重载则重新执行模块代码使 `loadSeq` 升为 `2`、`hits` 归零。

当模块 A 与模块 B 相互 `require` 形成循环依赖时,Node.js 会返回尚未执行完毕的半成品导出对象以防止死循环:实测 `a.cjs` 引入 `b.cjs`、`b.cjs` 回引 `a.cjs` 时,`b.cjs` 读到 `a.message` 为 `undefined`(Node.js v24 同时会输出循环依赖属性访问告警),随后 `a.cjs` 读到 `b.message` 为 `'Hello from b'`。另外 Node.js 在执行每个 CommonJS 模块前都会用五参包装函数 `(function(exports, require, module, __filename, __dirname) { ... })` 包裹源码(实测核验 `Module.wrapper[0]` 包含全部五参),因此顶层变量天然隔离、不会污染全局作用域。

require() 模块查找策略与解析顺序

`require(X)` 面对缓存、原生核心模块及三类文件模块时遵循严格优先级:首先检查文件模块缓存(已缓存则直接返回);其次检查是否属于原生核心模块(原生模块同样带独立缓存,且优先级高于同名本地目录,故即使当前目录存在 `http.js`,`require('http')` 仍加载内置模块)。

若既未命中缓存又非原生模块,则按路径规则解析文件系统:`./`、`../` 或 `/` 开头路径依次尝试 `LOAD_AS_FILE`(精确文件 → `.js` → `.json` → `.node`)与 `LOAD_AS_DIRECTORY`(先查 `package.json` 的 `main` 字段,否则查 `index.js`/`index.json`/`index.node`);裸模块名则沿当前目录逐级向上遍历各级 `node_modules` 查找,全部失败抛出 `MODULE_NOT_FOUND`。本站离线实测完整复现了 `node_modules/demo-pkg`(经 `package.json` `main` 指向 `lib/entry.cjs`)、目录默认 `index.js` 以及无后缀 `./config` 自动加载 `config.json` 三类解析路径。

实测内置与自定义 CJS 导出差异、ESM 动态导入、缓存刷新、循环依赖包装器及 require 路径解析

含完整源码 · 189 行
展开查看收起
javascript
import fsp from 'node:fs/promises';
import Module, { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

function deepEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mbsky-node-mod-'));

try {
  const req = createRequire(path.join(tmpDir, 'entry.cjs'));

  // Case 1: Built-in modules & custom CommonJS (exports vs module.exports vs broken exports reassignment)
  const osMod = req('node:os');
  const pathMod = req('node:path');

  const expFnPath = path.join(tmpDir, 'hello-exports.cjs');
  await fsp.writeFile(
    expFnPath,
    `exports.world = function () { return 'Hello World'; };\n`,
    'utf8',
  );

  const expClassPath = path.join(tmpDir, 'hello-class.cjs');
  await fsp.writeFile(
    expClassPath,
    `function Hello() {
  let name = '';
  this.setName = function (n) { name = n; };
  this.sayHello = function () { return 'Hello ' + name; };
}
module.exports = Hello;
`,
    'utf8',
  );

  const brokenExpPath = path.join(tmpDir, 'broken-exports.cjs');
  await fsp.writeFile(
    brokenExpPath,
    `exports = { secret: 42 };\n`,
    'utf8',
  );

  const helloMod = req('./hello-exports.cjs');
  const HelloCtor = req('./hello-class.cjs');
  const h = new HelloCtor();
  h.setName('NodeUser');
  const brokenMod = req('./broken-exports.cjs');

  const actual1 = {
    builtinHasPlatform: typeof osMod.platform() === 'string' && osMod.totalmem() > 0,
    pathJoined: pathMod.posix.join('a', 'b.js'),
    exportsWorld: helloMod.world(),
    classGreeting: h.sayHello(),
    brokenReassignKeys: Object.keys(brokenMod),
  };
  const expected1 = {
    builtinHasPlatform: true,
    pathJoined: 'a/b.js',
    exportsWorld: 'Hello World',
    classGreeting: 'Hello NodeUser',
    brokenReassignKeys: [],
  };

  // Case 2: ES Module export & dynamic import()
  const esmPath = path.join(tmpDir, 'myModule.mjs');
  await fsp.writeFile(
    esmPath,
    `export function greet(name) { return \`Hello, \${name}!\`; }\n`,
    'utf8',
  );
  const esmMod = await import(pathToFileURL(esmPath).href);
  const actual2 = { greetBob: esmMod.greet('Bob') };
  const expected2 = { greetBob: 'Hello, Bob!' };

  // Case 3: Module cache reuse and cache deletion reload
  const counterPath = path.join(tmpDir, 'counter.cjs');
  await fsp.writeFile(
    counterPath,
    `globalThis.__mbskyLoadCount = (globalThis.__mbskyLoadCount || 0) + 1;
module.exports = { loadSeq: globalThis.__mbskyLoadCount, hits: 0 };
`,
    'utf8',
  );
  const cFirst = req('./counter.cjs');
  cFirst.hits += 1;
  const cCached = req('./counter.cjs');
  const sameRef = cFirst === cCached;
  delete req.cache[req.resolve('./counter.cjs')];
  const cReloaded = req('./counter.cjs');
  delete globalThis.__mbskyLoadCount;

  const actual3 = {
    sameRef,
    cachedLoadSeq: cCached.loadSeq,
    cachedHits: cCached.hits,
    reloadedLoadSeq: cReloaded.loadSeq,
    reloadedHits: cReloaded.hits,
  };
  const expected3 = {
    sameRef: true,
    cachedLoadSeq: 1,
    cachedHits: 1,
    reloadedLoadSeq: 2,
    reloadedHits: 0,
  };

  // Case 4: Circular dependency partial export + Module.wrapper scope isolation
  const aPath = path.join(tmpDir, 'a.cjs');
  const bPath = path.join(tmpDir, 'b.cjs');
  await fsp.writeFile(
    aPath,
    `const log = globalThis.__mbskyCircLog;
const b = require('./b.cjs');
log.push('a_sees_b:' + b.message);
module.exports = { message: 'Hello from a' };
`,
    'utf8',
  );
  await fsp.writeFile(
    bPath,
    `const log = globalThis.__mbskyCircLog;
const a = require('./a.cjs');
log.push('b_sees_a:' + String(a.message));
module.exports = { message: 'Hello from b' };
`,
    'utf8',
  );
  globalThis.__mbskyCircLog = [];
  req('./a.cjs');
  const circLog = [...globalThis.__mbskyCircLog];
  delete globalThis.__mbskyCircLog;

  const wrapperStart = Module.wrapper[0].trim();
  const actual4 = {
    circLog,
    wrapperHasFiveArgs:
      wrapperStart.includes('exports') &&
      wrapperStart.includes('require') &&
      wrapperStart.includes('module') &&
      wrapperStart.includes('__filename') &&
      wrapperStart.includes('__dirname'),
  };
  const expected4 = {
    circLog: ['b_sees_a:undefined', 'a_sees_b:Hello from b'],
    wrapperHasFiveArgs: true,
  };

  // Case 5: Resolution order: node_modules package.json main, directory index.js, .json loader
  const pkgLibDir = path.join(tmpDir, 'node_modules', 'demo-pkg', 'lib');
  const dirModPath = path.join(tmpDir, 'dir-mod');
  await fsp.mkdir(pkgLibDir, { recursive: true });
  await fsp.mkdir(dirModPath, { recursive: true });
  await fsp.writeFile(
    path.join(tmpDir, 'node_modules', 'demo-pkg', 'package.json'),
    JSON.stringify({ name: 'demo-pkg', main: 'lib/entry.cjs' }),
    'utf8',
  );
  await fsp.writeFile(path.join(pkgLibDir, 'entry.cjs'), `module.exports = { source: 'node_modules_main' };\n`, 'utf8');
  await fsp.writeFile(path.join(dirModPath, 'index.js'), `module.exports = { source: 'dir_index_js' };\n`, 'utf8');
  await fsp.writeFile(path.join(tmpDir, 'config.json'), JSON.stringify({ env: 'local', port: 3000 }), 'utf8');

  const actual5 = {
    pkg: req('demo-pkg').source,
    dirMod: req('./dir-mod').source,
    jsonMod: req('./config'),
  };
  const expected5 = {
    pkg: 'node_modules_main',
    dirMod: 'dir_index_js',
    jsonMod: { env: 'local', port: 3000 },
  };

  const cases = [
    { name: 'builtin_and_custom_cjs_exports', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
    { name: 'esm_static_and_dynamic_import', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
    { name: 'module_cache_and_invalidation', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
    { name: 'circular_dependency_and_wrapper', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
    { name: 'resolution_algorithm_and_node_modules', passed: deepEqual(actual5, expected5), expected: expected5, actual: actual5 },
  ];

  console.log(JSON.stringify({ version: process.version, cases }));
} finally {
  await fsp.rm(tmpDir, { recursive: true, force: true });
}
核对 exports 重赋值断链返回空对象、缓存删除重载递增 loadSeq、循环依赖 b 见 a.message 为 undefined 及 node_modules/index.js/json 三类解析。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1041.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1058.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为模块最终导出的是 `module.exports` 所指向的对象,`exports` 只是指向它的形参变量,直接重赋值会让 `exports` 指向新对象而断开与 `module.exports` 的关联;刷新缓存需先执行 `delete require.cache[require.resolve(path)]` 再重新 `require`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习