Search code examples
node.jshttp2koa2

Enabling Http2Stream in koa2 app


I7m trying to create a simple http2 server and want to make use of Http2Stream in the http2 module to push large assets. How can I incorporate it in my Koa2 app? currently my server is just a middleware that receives the ctx and next object and checks if the file exists and tries to send it out.

async server(ctx, next, ...arg){
    //check if file exists
    //if it exists, set the headers and mimetype and send file
}

Does the ctx object contain the functions needed to work with http2stream, or how can i extend it?


Solution

  • You can utilize the stream in ctx.res (which is the original node response) like so: ctx.res.stream

    Working example: Koa2 with http/2 - this one gets a file in the public folder (filename ist hardcoded here) and sends it through the stream (which then should be the http2stream). Just type https://localhost:8080/file in your browser. You need to place a file thefile.html in to ./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);
    

    Hope that helps