You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用npm workerpool包时出现process.send is not a function错误求助

解决process.send is not a function错误(workerpool + git-diff场景)

错误原因

这个错误是因为代码在非Worker线程/子进程环境中调用了仅在Worker环境才存在的process.send API,大概率是workerpool的使用方式有误——比如主线程误执行了Worker专属的注册逻辑。

修复步骤

1. 拆分Worker与主线程代码,添加环境判断

确保Worker文件仅在Worker环境中注册任务,避免主线程执行时触发错误:

// worker.js(Worker专属文件)
const workerpool = require('workerpool');
const gitDiff = require('git-diff');

// 定义diff计算函数
function calculateFileDiff(contentA, contentB) {
  return gitDiff(contentA, contentB, {
    // 根据需求配置git-diff参数,比如关闭颜色输出
    color: false
  });
}

// 仅在Worker环境中注册任务
if (!workerpool.isMainThread) {
  workerpool.worker({ calculateFileDiff });
}

2. 主线程正确初始化Worker池

主线程通过指定Worker文件路径创建专用Worker,不要直接在主线程中执行Worker的注册逻辑:

// main.js(主线程代码)
const workerpool = require('workerpool');
const fs = require('fs/promises');

async function main() {
  // 读取两个目标文件内容
  const [file1Content, file2Content] = await Promise.all([
    fs.readFile('./file1.txt', 'utf8'),
    fs.readFile('./file2.txt', 'utf8')
  ]);

  // 创建专用Worker池,指向Worker文件
  const pool = workerpool.pool('./worker.js');

  try {
    // 调用Worker中的diff计算函数
    const diffResult = await pool.exec('calculateFileDiff', [file1Content, file2Content]);
    console.log('Diff结果:', diffResult);
  } catch (error) {
    console.error('计算Diff失败:', error);
  } finally {
    // 执行完后终止Worker池
    await pool.terminate();
  }
}

main();

3. 验证npm脚本配置

确保npm run脚本执行的是主线程入口文件(比如main.js),而非Worker文件:

// package.json
{
  "scripts": {
    "calc-diff": "node main.js"
  }
}

内容的提问来源于stack exchange,提问作者Faraz Ansari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 16:20:17