laf icon indicating copy to clipboard operation
laf copied to clipboard

[Question] How does the function return a Stream?

Open amzqing opened this issue 3 years ago • 5 comments

Search before asking

  • [X] I had searched in the issues and found no similar issues.

Question

我的测试代码


const { Readable } = require('stream')

exports.main = async function (ctx: FunctionContext) {
    const stream = new Readable({
      read() {
        // 把字符串推送到流里
        for (let i = 0; i < 10; i++) {
          // console.log(i);
          this.push('test' + i);
        }
        this.push(null);
      },
    })
   var chunks = []
    stream.on('data', (chunk) => {
      chunks.push(chunk);
    });
  
    stream.on('end', () => {
      console.log('End of stream');
    });

retrun stream // 这是不行的!
}


问题

直接return无法响应,请问Laf是有什么特殊的处理方式?

预期结果

test0
test1
test2
...
test8
test9

amzqing avatar Feb 12 '23 15:02 amzqing

这段代码也没主动返回 stream 吧,执行符合预期才对。

maslow avatar Feb 14 '23 05:02 maslow

@maslow 我的意思是,laf的函数如何给客户端返回正确的stream流,直接retrun Readable测试是不行的,所以代码里没有写。直接retrun用postman测试也是不行的呀。

amzqing avatar Feb 14 '23 06:02 amzqing

这段代码也没主动返回 stream 吧,执行符合预期才对。

虽然被关了,但还是等一个有效答复。

amzqing avatar Feb 14 '23 06:02 amzqing

嗯,需要安排测试一下

maslow avatar Feb 14 '23 09:02 maslow

抱歉这么久才回复。

在云函数中返回 stream 和在 express 中相同,大概如下:

const response = ctx.response
stream.pipe(response)

// return 

当然你也可以不用 pipe,总之知道 response 也是一个 stream 就好了。

@see https://www.mariokandut.com/how-to-stream-to-an-http-response-in-node-js/

maslow avatar Feb 24 '23 17:02 maslow