Javascript 我如何在快递中流响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38788721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i stream response in express
提问by Amit Adhikari
I've been trying to get a express app to send the response as stream.
我一直在尝试让一个快速应用程序将响应作为流发送。
var Readable = require('stream').Readable;
var rs = Readable();
app.get('/report', function(req,res) {
res.statusCode = 200;
res.setHeader('Content-type', 'application/csv');
res.setHeader('Access-Control-Allow-Origin', '*');
// Header to force download
res.setHeader('Content-disposition', 'attachment; filename=Report.csv');
rs.pipe(res);
rs.push("USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD\n");
for (var i = 0; i < 10; i++) {
rs.push("23,John Doe,1234,500,SUBSCRIPITON,100,ACTIVE,30\n");
}
rs.push(null);
});
It does print in the console when i replace "rs.pipe(res)" by "rs.pipe(process.stdout)" but how to make it work in express app.
当我将“rs.pipe(res)”替换为“rs.pipe(process.stdout)”时,它确实会在控制台中打印,但如何使其在快速应用程序中工作。
Error: not implemented
at Readable._read (_stream_readable.js:465:22)
at Readable.read (_stream_readable.js:341:10)
at Readable.on (_stream_readable.js:720:14)
at Readable.pipe (_stream_readable.js:575:10)
at line "rs.pipe(res);"
回答by robertklep
You don't need a readable stream instance, just use res.write()
:
您不需要可读流实例,只需使用res.write()
:
res.write("USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD\n");
for (var i = 0; i < 10; i++) {
res.write("23,John Doe,1234,500,SUBSCRIPITON,100,ACTIVE,30\n");
}
res.end();
This works because in Express, res
is based on Node's own http.serverResponse
, so it inherits all its methods (like write
).
这是有效的,因为在 Express 中,res
基于 Node 自己的http.serverResponse
,因此它继承了它的所有方法(如write
)。
回答by Sagan
I was able to get this to work.
我能够让这个工作。
- Put this code in your Express router.
- Open a web browser
- Go to http://yourdomain/yourrouterpath/stream
- 将此代码放在您的 Express 路由器中。
- 打开网络浏览器
- 转到http://yourdomain/yourrouterpath/stream
...
...
router.get('/stream', function (req, res, next) {
//when using text/plain it did not stream
//without charset=utf-8, it only worked in Chrome, not Firefox
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
res.write("Thinking...");
sendAndSleep(res, 1);
});
var sendAndSleep = function (response, counter) {
if (counter > 10) {
response.end();
} else {
response.write(" ;i=" + counter);
counter++;
setTimeout(function () {
sendAndSleep(response, counter);
}, 1000)
};
};