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

如何在Node.js中使用Spawn将子进程数据返回至父进程?

解决Node.js spawn调用Python脚本无法返回数据的问题

你的问题核心在于异步操作的处理逻辑错误,spawn是异步执行的,没法像同步函数那样直接赋值获取结果,而且当前的回调使用和数据接收都有问题,下面是修正方案:

第一步:修正Child.js的逻辑

  1. stdout.on('data')可能多次触发(比如返回数据较大时会分块传输),所以要累加数据而不是直接覆盖
  2. 必须等子进程结束(close事件)后再调用回调,确保拿到完整的返回数据
  3. 把错误信息也通过回调传递,方便调用方处理

修改后的Child.js:

//Child.js:  Node.js file that executes a python script using spawn...
const { spawn } = require('child_process'); // 把require提到函数外,避免重复加载

function run_python_script(jsonString, callback) {
    //spawn new child process to call the python script
    const python = spawn('python3', ["-c", `from apps import python_app; python_app.run(${jsonString});`]);

    let dataToSend = '';
    // 累加接收的数据
    python.stdout.on('data', (data) => {
        dataToSend += data.toString();
    });

    // 处理错误输出
    python.stderr.on('data', (data) => {
        callback(`stderr: ${data}`, null);
    });

    // 子进程结束后,传递完整数据
    python.on('close', (code) => {
        if (code === 0) {
            callback(null, dataToSend);
        } else {
            callback(`子进程退出码: ${code}`, null);
        }
    });
}

module.exports = { run_python_script };

第二步:修正调用方的逻辑

异步操作的结果只能在回调里处理,不能直接同步赋值。你的回调函数(x)=>{return x}没有实际作用,要在回调里写后续的业务逻辑:

修改后的调用代码:

const Child = require('./Child.js');

let company_data = {
    "industry": "Financial Services",
    "revenue": 123456789
};
const jsonString = JSON.stringify(company_data);

// 用回调处理异步返回的结果
Child.run_python_script(jsonString, (error, result) => {
    if (error) {
        console.error('调用出错:', error);
        return;
    }
    console.log('Python返回的数据:', result);
    // 在这里处理result,比如赋值给变量、调用其他函数等
    // 比如:
    // let processedData = handleResult(result);
    // doSomethingElse(processedData);
});

关键说明

  • spawn是异步API,函数run_python_script不会立即返回结果,所以你之前的result = Child.run_python_script(...)必然得到undefined
  • 必须通过回调(或者Promise/async-await)来处理异步结果,这是Node.js异步编程的核心逻辑
  • 一定要监听子进程的close事件,而不是只监听data事件,确保数据接收完整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:15:46