在 koa2 应用程序中启用 Http2Stream
Enabling Http2Stream in koa2 app
我正在尝试创建一个简单的 http2 服务器,并希望利用 http2 模块中的 Http2Stream
来推送大型资产。如何将它合并到我的 Koa2 应用程序中?目前我的服务器只是一个中间件,它接收 ctx 和下一个对象并检查文件是否存在并尝试将其发送出去。
async server(ctx, next, ...arg){
//check if file exists
//if it exists, set the headers and mimetype and send file
}
ctx object
是否包含使用 http2stream
所需的功能,或者我如何扩展它?
您可以像这样利用 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);
希望对您有所帮助
我正在尝试创建一个简单的 http2 服务器,并希望利用 http2 模块中的 Http2Stream
来推送大型资产。如何将它合并到我的 Koa2 应用程序中?目前我的服务器只是一个中间件,它接收 ctx 和下一个对象并检查文件是否存在并尝试将其发送出去。
async server(ctx, next, ...arg){
//check if file exists
//if it exists, set the headers and mimetype and send file
}
ctx object
是否包含使用 http2stream
所需的功能,或者我如何扩展它?
您可以像这样利用 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);
希望对您有所帮助