如何让子进程写入Node中的http响应? [英] How to get child process to write to an http response in Node?

查看:115
本文介绍了如何让子进程写入Node中的http响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项艰巨的工作,我会分派给一个子进程.但是我希望子进程处理响应而不是主线程.因此,子进程会生成一个很大的旧JSON对象,但我不希望它将其发送回主进程.我只希望它自己发送回响应.

I have a big job that I fork to a child process. But I want the child process to handle the response instead of the main thread. So the child process generates a big old JSON object, but I don't want it to send it BACK to the main process. I just want it to send the response back itself.

function doWork(req,res) {

     // CALL CHILD PROCESS, And have the child res.json(bigObject)
}
app.get('/dowork', doWork);

我希望这个传递响应("res"),以便孩子写回它.有没有办法在Node中做到这一点?

I'd like this pass the response ('res'), so that the child writes back to it. Is there a way to do this in Node?

推荐答案

这是一个简单的express js服务器,它通过子进程回显参数:

Here's a simple express js server that echo's arguments by way of a child process:

const express = require('express')
var child = require("child_process");
const app = express()
const port = 3000

app.post('/echo', (req, res) => {
    var cp = child.spawn(
         "xargs", // subprocess
        [ "echo", ], // arguments to subprocess
        {"stdio":["pipe","pipe",process.stderr]}
    );
    cp.stdout.pipe(res)
    req.pipe(cp.stdin);
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

唯一真正的诀窍是知道在express.js中,请求和响应对象是可读/可写的流.

The only real trick ins knowing that in express.js, the request and response objects are readable / writable streams.

这篇关于如何让子进程写入Node中的http响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆