nodejs/http2

http2 client: end event not emitted if no data listener registered

robertkowalski opened this issue · 4 comments

The http2 client will not emit end, given no data listener is registered, even if the server ends the response.

The following code calls req.on('end') just in the case req.on('data') is registered.

'use strict';
require('../common');
const assert = require('assert');
const http2 = require('http2');

const testResBody = 'other stuff!\n';

const server = http2.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  res.end(testResBody);
});

server.listen(0, function() {
  const client = http2.connect(`http://localhost:${this.address().port}`);

  const headers = { ':path': '/' };
  const req = client.request(headers)
  req.setEncoding('utf8');

  // XXX: remove this and ` req.on('end')` is never called 
  let data = '';
  req.on('data', (d) => data += d);

  req.on('response', (headers) => {
    assert.ok('date' in headers,
              'Response headers contain a date.');
  });

  req.on('end', () => {
    server.close();
    process.exit();
  });
  req.end();
});

This is expected, as 'end'  does not trigger the stream to flow. You should manually call resume(), add a on('data') or on('readable') event. This is part of streams, not http2.

Have a look at:

doh!

man thank you, I got a bit rusty!