在 NodeJS 中,如何在特定字符串处终止流?

In NodeJS, how would I terminate a stream at a certain string of characters?

我有一个 Express 路由,当它被点击时,会生成一个单独的进程,然后将该进程的标准输出流式传输给用户。

我只对那个单独进程输出的第一部分感兴趣,并且想在标准输出包含特定字符集(例如,-----).

这是我的 ExpressJS 代码:

const express = require('express')
const router = express.Router()
const {spawn} = require('child_process')

router.post('/', function (req, res, next) {
  res.type('text')
  const program = spawn(
    './foo',
    {shell: false}
  )

  program.stdout.on('data', (data) => res.write(data))
  program.on('close', (code) => res.end())
  req.on('close', (err) => {
    program.kill(15)
  })
})

这是我的过程中的一些示例标准输出:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse molestie porttitor nulla, mattis laoreet arcu ullamcorper vel.
Fusce dapibus mollis dui, vel ornare nulla fermentum quis.
-----
Pellentesque fringilla convallis purus, sit amet laoreet quam ornare eu.
Curabitur ut ultricies urna.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae
-----
Proin varius laoreet blandit. Proin pulvinar a augue non volutpat.

在此示例中,我想在终止进程并调用 res.end().

之前流式传输以下内容
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse molestie porttitor nulla, mattis laoreet arcu ullamcorper vel.
Fusce dapibus mollis dui, vel ornare nulla fermentum quis.

我已经为你做了这个例子。希望对你有用:-)

const fs = require('fs')

const rs = fs.createReadStream('./lorem.txt')

let keepReading = true;

rs.on('data', data => {

  if (keepReading) {
    const lines = data.toString().split('\n');
    let selectedText = ''

    for (const line of lines) {
      if (line.includes('-----')) {
        keepReading = false;
      }
      if (keepReading) {
        if (selectedText) {
          selectedText += '\n' + line;
        } else {
          selectedText += line;
        }
      }
    }
    process.stdout.write(selectedText)
  }
})
rs.on('close', code => process.exit(code))

请注意 rs 等同于您的 program