import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const cases = [];
// Case 1: hello_js_runtime_verification
{
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch05-hello-'));
try {
const helloPath = path.join(tmpDir, 'hello.js');
fs.writeFileSync(
helloPath,
[
"console.log('Hello, Node.js!');",
"console.log('Node.js 版本:', process.version);",
"console.log('当前工作目录:', process.cwd());",
"console.log('操作系统:', process.platform);",
].join('\n'),
'utf8'
);
const run = spawnSync(process.execPath, [helloPath], { cwd: tmpDir, encoding: 'utf8' });
const lines = run.stdout.trim().split(/\r?\n/);
const actual = {
exitCode: run.status,
lineCount: lines.length,
greeting: lines[0],
versionLine: lines[1],
cwdMatches: lines[2] === `当前工作目录: ${fs.realpathSync(tmpDir)}` || lines[2] === `当前工作目录: ${tmpDir}`,
platformLine: lines[3],
};
const expected = {
exitCode: 0,
lineCount: 4,
greeting: 'Hello, Node.js!',
versionLine: `Node.js 版本: ${process.version}`,
cwdMatches: true,
platformLine: `操作系统: ${process.platform}`,
};
cases.push({
name: 'hello_js_runtime_verification',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
// Case 2: nvmrc_project_version_switching
{
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch05-nvmrc-'));
try {
const projA = path.join(tmpDir, 'project-a');
const projB = path.join(tmpDir, 'project-b');
fs.mkdirSync(projA, { recursive: true });
fs.mkdirSync(projB, { recursive: true });
fs.writeFileSync(path.join(projA, '.nvmrc'), '18.17.0\n', 'utf8');
fs.writeFileSync(path.join(projB, '.nvmrc'), '16.20.1\n', 'utf8');
const installed = ['16.20.1', '18.17.0', '24.22.3'];
const defaultAlias = '18.17.0';
const resolveForDir = (dir) => {
const rc = path.join(dir, '.nvmrc');
const target = fs.existsSync(rc) ? fs.readFileSync(rc, 'utf8').trim() : defaultAlias;
return installed.includes(target) ? `v${target}` : null;
};
const actual = {
projectA: resolveForDir(projA),
projectB: resolveForDir(projB),
fallbackDefault: resolveForDir(tmpDir),
};
const expected = {
projectA: 'v18.17.0',
projectB: 'v16.20.1',
fallbackDefault: 'v18.17.0',
};
cases.push({
name: 'nvmrc_project_version_switching',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
// Case 3: version_comparison_and_lts_upgrade
{
const parseSemver = (v) => v.replace(/^v/, '').split('.').map(Number);
const cmp = (a, b) => {
const pa = parseSemver(a);
const pb = parseSemver(b);
for (let i = 0; i < 3; i++) {
if (pa[i] !== pb[i]) return pa[i] - pb[i];
}
return 0;
};
const pool = ['v24.22.3', 'v16.20.1', 'v18.17.0', 'v20.18.0'];
const sorted = [...pool].sort(cmp);
const actual = {
oldest: sorted[0],
newest: sorted[sorted.length - 1],
sortedCount: sorted.length,
satisfiesNode18Plus: cmp(process.version, 'v18.0.0') >= 0,
};
const expected = {
oldest: 'v16.20.1',
newest: 'v24.22.3',
sortedCount: 4,
satisfiesNode18Plus: true,
};
cases.push({
name: 'version_comparison_and_lts_upgrade',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
}
// Case 4: executable_path_and_prefix_inspection
{
const execDir = path.dirname(process.execPath);
const execBase = path.basename(process.execPath).toLowerCase();
const actual = {
execExists: fs.existsSync(process.execPath),
execDirExists: fs.existsSync(execDir),
binaryIsNode: execBase === 'node.exe' || execBase === 'node',
};
const expected = {
execExists: true,
execDirExists: true,
binaryIsNode: true,
};
cases.push({
name: 'executable_path_and_prefix_inspection',
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-nvm-lab/explore-nvm.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-nvm.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1064.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip