简体   繁体   English

如何从 Node.js 中的分叉子进程正确发送 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ?

[英]How can i properly send a stream from forked child process in Node.js?

I tried something like this in the forked child process:我在分叉的子进程中尝试了这样的事情:

WriterPlugin.js (child process) WriterPlugin.js(子进程)

 function sendCursor(){ try { let cursor = await getQueryCursor(reqBody, db); cursor.on('data', (data) => { process.send(data); }) } catch (error) { process.send({ message: error.toString(), status: 400 }) } }

controller.js (parent process) controller.js(父进程)

 const childProcess = fork(fileToExec); childProcess.send(objectToProcess); childProcess.on('message', (data) => { reply.send(data); })

This one printed just last data of cursor and i faced with a fastifyError:这个打印了 cursor 的最后一个数据,我遇到了 fastifyError:

 "code":"FST_ERR_REP_ALREADY_SENT","statusCode":500},"msg":"Reply already sent"}

How can i properly handle the cursor.stream() from a forked child process using fastify?如何使用 fastify 正确处理来自分叉子进程的cursor.stream()

You need to push the data into a stream to accomplish this task:您需要将数据推送到 stream 以完成此任务:

const { fork } = require('child_process')
const { Readable } = require('stream')

const fastify = require('fastify')()

fastify.get('/', (request, reply) => {
  const stream = new Readable({
    read (size) {}
  })

  const childProcess = fork('./external-file.js')
  childProcess.on('message', (data) => {
    stream.push(JSON.stringify(data)) // it must be a string
  })
  childProcess.on('close', (data) => {
    stream.push(null)
  })

  reply.send(stream)
})

fastify.listen(8080)

Where external-file.js is: external-file.js在哪里:

let iteration = 0
const timer = setInterval(() => {
  const data = { iteration: iteration++ }
  process.send(data)

  if (iteration === 3) {
    clearInterval(timer)
  }
}, 1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM