• stream {Http2Stream} A reference to the stream
    • headers {HTTP/2 Headers Object} An object describing the headers
    • flags {number} The associated numeric flags
    • rawHeaders {Array} An array containing the raw header names followed by their respective values.

    The 'stream' event is emitted when a new Http2Stream is created.

    1. const http2 = require('http2');
    2. session.on('stream', (stream, headers, flags) => {
    3. const method = headers[':method'];
    4. const path = headers[':path'];
    5. // ...
    6. stream.respond({
    7. ':status': 200,
    8. 'content-type': 'text/plain; charset=utf-8'
    9. });
    10. stream.write('hello ');
    11. stream.end('world');
    12. });

    On the server side, user code will typically not listen for this event directly, and would instead register a handler for the 'stream' event emitted by the net.Server or tls.Server instances returned by http2.createServer() and http2.createSecureServer(), respectively, as in the example below:

    1. const http2 = require('http2');
    2. // Create an unencrypted HTTP/2 server
    3. const server = http2.createServer();
    4. server.on('stream', (stream, headers) => {
    5. stream.respond({
    6. 'content-type': 'text/html; charset=utf-8',
    7. ':status': 200
    8. });
    9. stream.on('error', (error) => console.error(error));
    10. stream.end('<h1>Hello World</h1>');
    11. });
    12. server.listen(80);

    Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, a network error will destroy each individual stream and must be handled on the stream level, as shown above.