import { exec, execFile, spawn, fork } from 'node:child_process';
import http from 'node:http';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function runExec(cmd) {
return new Promise((resolve, reject) => {
let exitCode = null;
const child = exec(cmd, { encoding: 'utf8' }, (err, stdout, stderr) => {
if (err) return reject(err);
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), exitCode });
});
child.on('exit', (code) => {
exitCode = code;
});
});
}
function runExecFile(bin, args) {
return new Promise((resolve, reject) => {
execFile(bin, args, { encoding: 'utf8' }, (err, stdout, stderr) => {
if (err) return reject(err);
resolve({ stdout: stdout.trim(), stderr: stderr.trim() });
});
});
}
function runSpawn(bin, args) {
return new Promise((resolve, reject) => {
const child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (d) => {
stdout += d;
});
child.stderr.on('data', (d) => {
stderr += d;
});
child.on('error', reject);
child.on('close', (code) => {
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code });
});
});
}
class MiniProcessPool {
constructor(workerFile, size) {
this.workerFile = workerFile;
this.idle = [];
this.all = [];
this.queue = [];
this.pending = new Map();
this.seq = 0;
for (let i = 0; i < size; i++) {
const w = fork(workerFile, [], { silent: true });
w.on('message', (msg) => {
if (msg?.type === 'done') {
const entry = this.pending.get(msg.id);
if (entry) {
this.pending.delete(msg.id);
entry.resolve({ result: msg.result, pid: msg.pid });
}
this.idle.push(w);
this._drain();
}
});
this.idle.push(w);
this.all.push(w);
}
}
_drain() {
while (this.queue.length > 0 && this.idle.length > 0) {
const task = this.queue.shift();
const w = this.idle.shift();
this.pending.set(task.id, task);
w.send({ type: 'task', id: task.id, n: task.n });
}
}
runTask(n) {
const id = `t${++this.seq}`;
return new Promise((resolve, reject) => {
this.queue.push({ id, n, resolve, reject });
this._drain();
});
}
async close() {
await Promise.all(
this.all.map(
(w) =>
new Promise((resolve) => {
if (w.exitCode !== null) return resolve();
w.once('exit', () => resolve());
w.send({ type: 'shutdown' });
}),
),
);
}
}
async function main() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-proc-'));
const supportPath = path.join(tmpDir, 'support.mjs');
const workerPath = path.join(tmpDir, 'worker.mjs');
await fs.writeFile(
supportPath,
'console.log("进程 " + process.argv[2] + " 执行。");\n',
'utf8',
);
await fs.writeFile(
workerPath,
[
'function fib(n) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); }',
'process.on("message", (msg) => {',
' if (msg.type === "task") {',
' process.send({ type: "done", id: msg.id, result: fib(msg.n), pid: process.pid });',
' } else if (msg.type === "shutdown") {',
' process.exit(0);',
' }',
'});',
].join('\n'),
'utf8',
);
const cases = [];
try {
// Case 1: child_process_exec_and_execfile
const execResults = await Promise.all(
[0, 1, 2].map((i) => runExec(`"${process.execPath}" "${supportPath}" ${i}`)),
);
const execFileRes = await runExecFile(process.execPath, [supportPath, 'safe']);
const actual1 = {
execOutputs: execResults.map((r) => r.stdout).sort(),
execCodes: execResults.map((r) => r.exitCode),
execFileStdout: execFileRes.stdout,
};
const expected1 = {
execOutputs: ['进程 0 执行。', '进程 1 执行。', '进程 2 执行。'],
execCodes: [0, 0, 0],
execFileStdout: '进程 safe 执行。',
};
cases.push({
name: 'child_process_exec_and_execfile',
passed: JSON.stringify(actual1) === JSON.stringify(expected1),
expected: expected1,
actual: actual1,
});
// Case 2: child_process_spawn_streams
const spawnResults = await Promise.all(
[0, 1, 2].map((i) => runSpawn(process.execPath, [supportPath, String(i)])),
);
const actual2 = {
outputs: spawnResults.map((r) => r.stdout).sort(),
codes: spawnResults.map((r) => r.code),
stderrEmpty: spawnResults.every((r) => r.stderr === ''),
};
const expected2 = {
outputs: ['进程 0 执行。', '进程 1 执行。', '进程 2 执行。'],
codes: [0, 0, 0],
stderrEmpty: true,
};
cases.push({
name: 'child_process_spawn_streams',
passed: JSON.stringify(actual2) === JSON.stringify(expected2),
expected: expected2,
actual: actual2,
});
// Case 3: child_process_fork_ipc
const ipcResult = await new Promise((resolve, reject) => {
const child = fork(workerPath, ['w1'], { silent: true });
let reply = null;
child.on('error', reject);
child.on('message', (msg) => {
reply = msg;
child.send({ type: 'shutdown' });
});
child.on('close', (code) => {
resolve({
id: reply?.id,
result: reply?.result,
distinctPid: typeof reply?.pid === 'number' && reply.pid !== process.pid,
exitCode: code,
});
});
child.send({ type: 'task', id: 't1', n: 20 });
});
const expected3 = { id: 't1', result: 6765, distinctPid: true, exitCode: 0 };
cases.push({
name: 'child_process_fork_ipc',
passed: JSON.stringify(ipcResult) === JSON.stringify(expected3),
expected: expected3,
actual: ipcResult,
});
// Case 4: process_pool_reuse_and_http_offload
const pool = new MiniProcessPool(workerPath, 2);
const server = http.createServer(async (req, res) => {
const url = new URL(req.url || '/', 'http://127.0.0.1');
if (url.pathname === '/fib') {
const n = Number(url.searchParams.get('n') || 10);
const { result } = await pool.runTask(n);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ n, result }));
return;
}
res.writeHead(404).end('Not Found');
});
try {
const batchInputs = [10, 12, 15, 18, 20, 21];
const batchOut = await Promise.all(batchInputs.map((n) => pool.runTask(n)));
const workerPids = new Set(batchOut.map((o) => o.pid));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const httpRes = await fetch(`http://127.0.0.1:${port}/fib?n=20`);
const httpJson = await httpRes.json();
const actual4 = {
results: batchOut.map((o) => o.result),
reusedWithinPoolSize: workerPids.size >= 1 && workerPids.size <= 2,
httpStatus: httpRes.status,
httpBody: httpJson,
};
const expected4 = {
results: [55, 144, 610, 2584, 6765, 10946],
reusedWithinPoolSize: true,
httpStatus: 200,
httpBody: { n: 20, result: 6765 },
};
cases.push({
name: 'process_pool_reuse_and_http_offload',
passed: JSON.stringify(actual4) === JSON.stringify(expected4),
expected: expected4,
actual: actual4,
});
} finally {
await new Promise((resolve) => server.close(resolve));
await pool.close();
}
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
console.log(JSON.stringify({ version: process.version, cases }));
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/nodejs-process-lab/explore-process.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-process.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1066.zip