我一直在尝试使用快速应用程序将响应作为流发送。
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);
});
当我用“rs.pipe(process.stdout)”替换“rs.pipe(res)”时,它会在控制台中打印,但是如何使它在Express应用程序中运行。
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);"
答案 0 :(得分:13)
您不需要可读的流实例,只需使用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();
这是有效的,因为在Express中,res
基于节点自己的http.serverResponse
,因此它会继承其所有方法(例如write
)。
答案 1 :(得分:0)
我能够做到这一点。
...
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)
};
};
答案 2 :(得分:0)
为了使用tar-stream,我需要以快速方式发送响应。这是我的处理方法,以防它对任何人都有帮助。
请求是针对服务器上存储的tar文件中的单个文件。
const fs = require("fs"),
tar = require("tar-stream");
app.get("/fileFromTar/*", (req, res) => {
const fileWanted = req.params[0],
readStream = fs.createReadStream('myTarFile.tar'),
extractor = tar.extract();
extractor.on('entry', (header, stream, next) => {
stream.on('end', next);
if (header.name === fileWanted) {
const { size } = header;
res.set({
"Content-Type": 'audio/flac', // or whichever one applies
"Content-Length": size,
"Content-Range": `bytes 0-${size}/${size}`
});
stream.pipe(res);
}
else stream.resume();
});
readStream.pipe(extractor);
});