我怎样才能正确地从 Node.js 中的分叉子进程发送流?

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

我在分叉的子进程中尝试过这样的事情:

WriterPlugin.js(子进程) </p> <pre><code> 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(父进程)

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

这个只打印了光标的最后一个数据,我遇到了一个 fastifyError: </p> <pre><code>"code":"FST_ERR_REP_ALREADY_SENT","statusCode":500},"msg":"Reply already sent"}

我如何正确地处理 来自使用 fastify 的分叉子进程的 cursor.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)

其中 external-file.js 是:

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

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