Windows10下Node.js如何并行spawn子进程,独立计时5秒终止HLS流录制
问题根因
原来的实现存在三个核心问题,导致串行执行和功能异常:
- 循环内直接
await setTimeout:JS 单线程执行遇到 await 会阻塞当前循环逻辑,每启动一个进程就必须等5秒完成杀进程后,才会进入下一次循环,5个流总耗时会达到25秒 - 变量名拼写错误:循环内引用了未定义的
urls[i],实际定义的流数组是hls_streams[i],运行会直接报错 - Windows 环境兼容缺失:直接调用
child.kill()无法终止完整的进程树,容易残留后台streamlink进程,且spawn默认配置无法识别Windows下pip安装的.cmd格式streamlink脚本
正确实现方案
核心思路是把单个流的「启动录制→等待5秒→终止进程」逻辑封装为独立的异步任务,所有任务同时并行启动,通过Promise.all统一等待所有任务完成,总耗时就会稳定在5秒左右。
完整可运行代码
import { spawn } from "child_process"; import crypto from "crypto" import os from "os" import path from "path" import fs from "fs" const hls_streams = [ 'https://stream1.url', 'https://stream2.url', 'https://stream3.url', 'https://stream4.url', 'https://stream5.url', ] // 单个流的独立录制逻辑 async function recordOneStream(streamUrl, outputDir) { const filename = crypto.randomBytes(16).toString("hex"); // Windows 兼容配置: // shell: true 识别.cmd格式的streamlink脚本 // detached: true 让子进程成为独立进程组的头,方便后续整体终止 const child = spawn('streamlink', [ streamUrl, "best", "-f", "-o", path.join(outputDir, `${filename}.mp4`) ], { shell: true, detached: true }); // 独立等待5秒计时,不阻塞其他流的任务 await new Promise(resolve => setTimeout(resolve, 5000)); // Windows下终止整个进程树,避免残留后台进程 try { process.kill(-child.pid); } catch (err) { // 兜底终止主进程 child.kill(); } console.log(`流录制完成:${streamUrl}`); } // 并行启动所有流的录制任务 async function runAllRecord() { // 用系统临时目录做输出,避免Windows路径解析问题 const outputDir = path.join(os.tmpdir(), 'stream_records'); // 提前创建输出目录 fs.mkdirSync(outputDir, { recursive: true }); // 并行生成所有录制任务的Promise,同时启动 const recordTasks = hls_streams.map(url => recordOneStream(url, outputDir)); // 等待所有任务完成,总耗时约5秒 await Promise.all(recordTasks); console.log('所有流录制任务执行完毕'); } runAllRecord().catch(err => console.error('任务执行失败:', err));
关键注意事项
- 并行原理:所有录制任务的Promise在数组
map阶段就已经同时启动,不存在循环阻塞的问题,每个任务独立运行5秒计时逻辑,任务间无等待关系 - 路径兼容:代码自动适配Windows系统临时目录,避免硬写
/temp这种类Unix路径在Windows下解析失败;如果自定义输出目录,需要提前手动创建对应文件夹,避免文件写入报错 - 进程清理:通过负PID杀进程组的配置,是解决Windows下spawn派生进程残留的核心方案——默认
child.kill()仅能终止spawn的壳进程,无法关闭后台实际运行的streamlink程序,容易导致资源占用 - streamlink调用兼容:spawn配置里的
shell: true是Windows下pip安装streamlink的必需配置,否则会因为找不到.cmd格式的脚本直接报错
内容的提问来源于stack exchange,提问作者jeflopodev
相关产品推荐
相关产品推荐

