import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import repl from 'node:repl';
import { PassThrough } from 'node:stream';
function runReplSession(lines) {
return new Promise((resolve) => {
const input = new PassThrough();
const output = new PassThrough();
let collected = '';
output.setEncoding('utf8');
output.on('data', (chunk) => {
collected += chunk;
});
const server = repl.start({
prompt: '> ',
input,
output,
terminal: false,
useColors: false,
preview: false,
});
server.on('exit', () => {
resolve({ output: collected, context: server.context });
});
for (const line of lines) {
input.write(`${line}\n`);
}
input.write('.exit\n');
input.end();
});
}
const cases = [];
// Case 1: repl_expressions_and_variables
{
const { context } = await runReplSession([
'var a1 = 1 + 4',
'var a2 = 5 / 2',
'var a3 = 3 * 6',
'var a4 = 4 - 1',
'var a5 = 1 + ( 2 * 3 ) - 4',
'x = 10',
'var y = 10',
'var total = x + y',
]);
const actual = {
add: context.a1,
div: context.a2,
mul: context.a3,
sub: context.a4,
grouped: context.a5,
xPlusY: context.total,
};
const expected = {
add: 5,
div: 2.5,
mul: 18,
sub: 3,
grouped: 3,
xPlusY: 20,
};
cases.push({
name: 'repl_expressions_and_variables',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
}
// Case 2: repl_multiline_do_while
{
const { context } = await runReplSession([
'var x = 0',
'var logs = []',
'do {',
'x++;',
'logs.push("x: " + x);',
'} while ( x < 5 );',
]);
const actual = {
finalX: context.x,
logs: context.logs,
};
const expected = {
finalX: 5,
logs: ['x: 1', 'x: 2', 'x: 3', 'x: 4', 'x: 5'],
};
cases.push({
name: 'repl_multiline_do_while',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
}
// Case 3: repl_underscore_result_cache
{
const { context } = await runReplSession([
'var x = 10',
'var y = 20',
'x + y',
'var sum = _',
'5 + 5',
'var doubled = _ * 2',
]);
const actual = {
sum: context.sum,
doubled: context.doubled,
};
const expected = {
sum: 30,
doubled: 20,
};
cases.push({
name: 'repl_underscore_result_cache',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
}
// Case 4: repl_dot_commands_and_completion
{
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch10-repl-'));
try {
const savePath = path.join(tmpDir, 'session.js');
const { output: helpOut } = await runReplSession(['.help']);
const expectedCmds = ['.break', '.clear', '.exit', '.help', '.load', '.save'];
const allHelpCmdsListed = expectedCmds.every((cmd) => helpOut.includes(cmd));
const { context: ctxSaveLoad } = await runReplSession([
'var savedVal = 42',
`.save ${savePath}`,
'.clear',
'var afterClearType = typeof savedVal',
`.load ${savePath}`,
'var restoredVal = savedVal',
]);
const input = new PassThrough();
const output = new PassThrough();
const compServer = repl.start({ input, output, terminal: false, useColors: false, preview: false });
const completions = await new Promise((resolve, reject) => {
compServer.completer('cons', (err, result) => {
if (err) reject(err);
else resolve(result[0]);
});
});
compServer.close();
const actual = {
allHelpCmdsListed,
savedFileExists: fs.existsSync(savePath),
afterClearType: ctxSaveLoad.afterClearType,
restoredVal: ctxSaveLoad.restoredVal,
completesConsole: completions.includes('console'),
};
const expected = {
allHelpCmdsListed: true,
savedFileExists: true,
afterClearType: 'undefined',
restoredVal: 42,
completesConsole: true,
};
cases.push({
name: 'repl_dot_commands_and_completion',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/nodejs-repl-lab/explore-repl.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-repl.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1069.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip