stream
{Http2Stream} A reference to the streamheaders
{HTTP/2 Headers Object} An object describing the headersflags
{number} The associated numeric flagsrawHeaders
{Array} An array containing the raw header names followed by their respective values.
The 'stream'
event is emitted when a new Http2Stream
is created.
const http2 = require('http2');
session.on('stream', (stream, headers, flags) => {
const method = headers[':method'];
const path = headers[':path'];
// ...
stream.respond({
':status': 200,
'content-type': 'text/plain; charset=utf-8'
});
stream.write('hello ');
stream.end('world');
});
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:
const http2 = require('http2');
// Create an unencrypted HTTP/2 server
const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200
});
stream.on('error', (error) => console.error(error));
stream.end('<h1>Hello World</h1>');
});
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.