简体   繁体   English

expressjs - 管道到响应流不起作用

[英]expressjs - piping to response stream doesn't work

I have this basic express app: 我有这个基本的快递应用程序:

var express = require('express');
var app = express();
var PORT = 3000;
var through = require('through');


function write(buf) {
    console.log('writing...');
    this.queue('okkkk');
}

function end() {
    this.queue(null);
}

var str = through(write, end);


/* routes */
app.get('/', function(req, res){
    res.send("Hello!");
})


app.post('/stream', function(req, res){
    var s = req.pipe(str).pipe(res);
    s.on('finish', function() {
       console.log('all writes are now complete.'); // printed the first time
    });
});


/* listen */
app.listen(PORT, function () {
    console.log('listening on port ' + PORT + '...');
});

When I post some data to /stream endpoint for the first time after starting the server I get okkk as the response which is what I expect. 当我在启动服务器后第一次将一些数据发布到/stream端点时,我得到okkk作为响应,这是我所期望的。 However, after that, any requests to /stream endpoint just timeout and not return any response. 但是,在此之后,对/stream endpoint的任何请求都会超时并且不会返回任何响应。

Why is it so? 为什么会这样? What's exactly happening here? 这到底发生了什么?

当我用req.pipe(through(write, end)).pipe(res)替换req.pipe(str).pipe(res)时,它工作了req.pipe(str).pipe(res)基本上确保为每个请求创建一个新的直通流实例。

I had this same problem and looks like res was not being finished properly. 我有同样的问题,看起来res没有正确完成。 So I added a callback to my stream and ended que res myself. 所以我在我的流中添加了一个回调并自己结束了que res That fixed my problem: 这解决了我的问题:

stream.on('end', () => res.end());
stream.pipe(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM