您可以使用ctx.res中的流(这是原始节点响应),如下所示:
ctx.res.stream
工作示例:带有http/2的Koa2-这个文件在
public
文件夹(文件名在此硬编码)并通过流发送(然后应该是
http2stream
)中。只是打字
https://localhost:8080/file
在浏览器中。你需要放一个文件
thefile.html
到
./public
以下内容:
'use strict';
const fs = require('fs');
const http2 = require('http2');
const koa = require('koa');
const app = new koa();
const options = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem'),
passphrase: 'test'
};
function getFile(path) {
const filePath = `${__dirname}/public/${path}`;
try {
const content = fs.openSync(filePath, 'r');
const contentType = 'text/html';
return {
content,
headers: {
'content-type': contentType
}
};
} catch (e) {
return null;
}
}
// response
app.use(ctx => {
if (ctx.request.url === '/file') {
const file = getFile('thefile.html');
ctx.res.stream.respondWithFD(file.content, file.headers);
} else {
ctx.body = 'OK' ;
}
});
const server = http2.createSecureServer(options, app.callback());
console.log('Listening on port 8080');
server.listen(8080);
希望能帮上忙