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

离线实测 pnpm 内容寻址硬链接复用、严格符号链接防幻影依赖、.npmrc 与 Workspace 协议解析

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-pnpm.mjs
explore-pnpm.mjs221 行
import crypto from 'node:crypto';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';

const cases = [];

// Case 1: content_addressable_hardlink_store
{
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch09-cas-'));
  try {
    const content = "module.exports = { pkg: 'demo-lodash', ver: '4.17.21' };\n";
    const digest = crypto.createHash('sha256').update(content).digest('hex');
    const storeFile = path.join(tmpDir, 'pnpm-store', digest.slice(0, 2), `${digest}.cjs`);
    fs.mkdirSync(path.dirname(storeFile), { recursive: true });
    fs.writeFileSync(storeFile, content, 'utf8');

    const projAFile = path.join(tmpDir, 'project-a', 'node_modules', '.pnpm', 'demo-lodash@4.17.21', 'index.cjs');
    const projBFile = path.join(tmpDir, 'project-b', 'node_modules', '.pnpm', 'demo-lodash@4.17.21', 'index.cjs');
    fs.mkdirSync(path.dirname(projAFile), { recursive: true });
    fs.mkdirSync(path.dirname(projBFile), { recursive: true });
    fs.linkSync(storeFile, projAFile);
    fs.linkSync(storeFile, projBFile);

    const stStore = fs.statSync(storeFile);
    const stA = fs.statSync(projAFile);
    const stB = fs.statSync(projBFile);
    const actual = {
      sameInodeStoreAndA: stStore.ino === stA.ino,
      sameInodeStoreAndB: stStore.ino === stB.ino,
      hardLinkCount: stStore.nlink,
      contentMatch: fs.readFileSync(projAFile, 'utf8') === fs.readFileSync(projBFile, 'utf8'),
    };
    const expected = {
      sameInodeStoreAndA: true,
      sameInodeStoreAndB: true,
      hardLinkCount: 3,
      contentMatch: true,
    };
    cases.push({
      name: 'content_addressable_hardlink_store',
      passed: JSON.stringify(actual) === JSON.stringify(expected),
      expected,
      actual,
    });
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

// Case 2: strict_symlink_node_modules_isolation
{
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch09-sym-'));
  try {
    const nmRoot = path.join(tmpDir, 'node_modules');
    const virtualPkgDir = path.join(nmRoot, '.pnpm', 'pkg-a@1.0.0', 'node_modules');
    const realPkgA = path.join(virtualPkgDir, 'pkg-a');
    const realHidden = path.join(virtualPkgDir, 'hidden-dep');
    fs.mkdirSync(realPkgA, { recursive: true });
    fs.mkdirSync(realHidden, { recursive: true });

    fs.writeFileSync(
      path.join(realHidden, 'package.json'),
      JSON.stringify({ name: 'hidden-dep', version: '1.0.0', main: 'index.cjs' }),
      'utf8'
    );
    fs.writeFileSync(path.join(realHidden, 'index.cjs'), "module.exports = 'secret-helper';\n", 'utf8');

    fs.writeFileSync(
      path.join(realPkgA, 'package.json'),
      JSON.stringify({ name: 'pkg-a', version: '1.0.0', main: 'index.cjs' }),
      'utf8'
    );
    fs.writeFileSync(
      path.join(realPkgA, 'index.cjs'),
      "const hidden = require('hidden-dep'); module.exports = { via: hidden };\n",
      'utf8'
    );

    const linkType = process.platform === 'win32' ? 'junction' : 'dir';
    fs.symlinkSync(realPkgA, path.join(nmRoot, 'pkg-a'), linkType);

    const appEntry = path.join(tmpDir, 'index.cjs');
    fs.writeFileSync(appEntry, '// app\n', 'utf8');
    const appReq = createRequire(appEntry);
    const directPkgA = appReq('pkg-a');

    let phantomBlocked = false;
    try {
      appReq('hidden-dep');
    } catch (err) {
      phantomBlocked = err.code === 'MODULE_NOT_FOUND';
    }

    const actual = {
      directPkgAResolved: directPkgA.via,
      phantomDependencyBlocked: phantomBlocked,
      topLevelIsSymlink: fs.lstatSync(path.join(nmRoot, 'pkg-a')).isSymbolicLink(),
    };
    const expected = {
      directPkgAResolved: 'secret-helper',
      phantomDependencyBlocked: true,
      topLevelIsSymlink: true,
    };
    cases.push({
      name: 'strict_symlink_node_modules_isolation',
      passed: JSON.stringify(actual) === JSON.stringify(expected),
      expected,
      actual,
    });
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

// Case 3: npmrc_and_workspace_yaml_config
{
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch09-ws-'));
  try {
    const npmrcText = [
      'registry=https://registry.npmmirror.com',
      'auto-install-peers=true',
      'strict-peer-dependencies=true',
      'shamefully-hoist=false',
      'node-linker=isolated',
    ].join('\n');
    const npmrc = Object.fromEntries(
      npmrcText
        .split('\n')
        .map((line) => line.trim())
        .filter((line) => line && !line.startsWith('#'))
        .map((line) => line.split('='))
    );

    const dirs = [
      'packages/package-a',
      'packages/package-b',
      'packages/test/ignored-pkg',
      'apps/web-app',
    ];
    for (const rel of dirs) {
      const full = path.join(tmpDir, rel);
      fs.mkdirSync(full, { recursive: true });
      fs.writeFileSync(
        path.join(full, 'package.json'),
        JSON.stringify({ name: path.basename(rel), version: '1.0.0' }),
        'utf8'
      );
    }

    const matched = [];
    for (const root of ['packages', 'apps']) {
      for (const entry of fs.readdirSync(path.join(tmpDir, root))) {
        if (entry === 'test') continue;
        const pkgJson = path.join(tmpDir, root, entry, 'package.json');
        if (fs.existsSync(pkgJson)) {
          matched.push(`${root}/${entry}`);
        }
      }
    }
    matched.sort();

    const actual = {
      registry: npmrc.registry,
      autoInstallPeers: npmrc['auto-install-peers'] === 'true',
      workspacePackages: matched,
    };
    const expected = {
      registry: 'https://registry.npmmirror.com',
      autoInstallPeers: true,
      workspacePackages: ['apps/web-app', 'packages/package-a', 'packages/package-b'],
    };
    cases.push({
      name: 'npmrc_and_workspace_yaml_config',
      passed: JSON.stringify(actual) === JSON.stringify(expected),
      expected,
      actual,
    });
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

// Case 4: workspace_protocol_and_command_mapping
{
  const localVersions = { 'package-a': '1.2.0', 'package-b': '1.3.0' };
  const resolveWorkspaceSpec = (name, spec) => {
    const ver = localVersions[name];
    if (spec === 'workspace:*') return ver;
    if (spec.startsWith('workspace:^')) return `^${ver}`;
    return spec;
  };
  const cmdMap = {
    'npm install <pkg>': 'pnpm add <pkg>',
    'npm install <pkg> --save-dev': 'pnpm add -D <pkg>',
    'npm uninstall <pkg>': 'pnpm remove <pkg>',
    'npx <command>': 'pnpm dlx <command>',
  };
  const actual = {
    starSpec: resolveWorkspaceSpec('package-a', 'workspace:*'),
    caretSpec: resolveWorkspaceSpec('package-b', 'workspace:^1.0.0'),
    addMapped: cmdMap['npm install <pkg>'],
    dlxMapped: cmdMap['npx <command>'],
  };
  const expected = {
    starSpec: '1.2.0',
    caretSpec: '^1.3.0',
    addMapped: 'pnpm add <pkg>',
    dlxMapped: 'pnpm dlx <command>',
  };
  cases.push({
    name: 'workspace_protocol_and_command_mapping',
    passed: JSON.stringify(actual) === JSON.stringify(expected),
    expected,
    actual,
  });
}

console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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