【问题标题】:Connection closed with request stream and asynchronous processing使用请求流和异步处理关闭连接
【发布时间】:2020-06-06 01:44:54
【问题描述】:

我在处理来自 HTTP 请求的流时遇到问题。处理程序从流中收集数据并在发送响应之前执行一些异步操作。

一旦收集到流数据,HTTP 连接就会在someAsyncStuff 被调用之前关闭。

这是重现问题的示例。我做错了什么?

import * as Busboy from 'busboy'
import * as express from 'express'
import { pipeline } from 'stream'
import concat = require('concat-stream')

const app = express()

app.post('/', (req, res) => {
  const busboy = new Busboy({ headers: req.headers })

  busboy.on('file', (_, file) => {
    pipeline(
      file,
      concat(buffer =>
        someAsyncStuff(buffer.toString())
          .then(length => res.send({ length }))
          .catch(err => res.status(500).send(err.message))
      ),
      err => {
        if (err) res.status(500).send(err.message)
      }
    )
  })

  pipeline(req, busboy, err => {
    if (err) res.status(500).send(err.message)
  })
})

function someAsyncStuff(s: string): Promise<number> {
  return new Promise(resolve => setTimeout(() => resolve(s.length), 1))
}

app.listen('3000')

【问题讨论】:

    标签: node.js express stream


    【解决方案1】:

    使用 req.pipe 似乎有效。

    import Busboy from 'busboy'
    import express from 'express'
    import { pipeline } from 'stream'
    import concat from 'concat-stream'
    
    const app = express()
    
    app.post('/', (req, res) => {
      const busboy = new Busboy({ headers: req.headers })
    
      busboy.on('file', (_, file) => {
        pipeline(
          file,
          concat(buffer =>
            someAsyncStuff(buffer.toString())
              .then(length => res.json({ length }))
              .catch(err => res.status(500).send(err.message))
          ),
          err => {
            if (err) res.status(500).send(err.message)
          }
        )
      })
      req.pipe(busboy);
    })
    
    function someAsyncStuff(s) {
      return new Promise(resolve => setTimeout(() => resolve(s.length), 1000))
    }
    
    app.listen('3000')
    

    【讨论】:

    • 它确实有效,谢谢!我还没有在我实际遇到问题的代码上尝试过。我也想了解为什么会这样。据我了解,使用pipeline 是管道流的最佳实践(用于错误处理和一些清理)。你能开导我吗?
    猜你喜欢
    • 2012-05-20
    • 2019-07-28
    • 2018-05-12
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2019-06-04
    相关资源
    最近更新 更多