node.js - 连接通过请求流和异步处理关闭

标签 node.js express stream

我在处理来自 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')

最佳答案

使用 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')

关于node.js - 连接通过请求流和异步处理关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60341860/

相关文章:

javascript - NodeJS 服务器更改 JSON 对象的键名

node.js - 如何将背压应用于 Node 流?

java - 使用 jOOλ 按属性总结 BigDecimal 分组

node.js - 嵌套 Jade 模板黑色

C++文件流

node.js - Node.js 中的 Azure Function 和共享文件

javascript - 错误 : Cannot find module './build/Release/sharp'

javascript - 获取 API 。我从自己的 express 服务器收到一个空字符串

node.js - CKEditor 内联于 Node.js

node.js - Oriento 查询生成器类似子句