蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-module-system.mjs
explore-module-system.mjs189 行
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 });
}
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/nodejs-module-system-lab/explore-module-system.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-module-system.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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