• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const { mustCall } = require('../common');
4
5const fs = require('fs');
6const http = require('http');
7const { strictEqual } = require('assert');
8
9const server = http.createServer(mustCall(function(req, res) {
10  strictEqual(req.socket.listenerCount('data'), 1);
11  req.socket.once('data', mustCall(function() {
12    // Ensure that a chunk of data is received before calling `res.end()`.
13    res.end('hello world');
14  }));
15  // This checks if the request gets dumped
16  // resume will be triggered by res.end().
17  req.on('resume', mustCall(function() {
18    // There is no 'data' event handler anymore
19    // it gets automatically removed when dumping the request.
20    strictEqual(req.listenerCount('data'), 0);
21    req.on('data', mustCall());
22  }));
23
24  // We explicitly pause the stream
25  // so that the following on('data') does not cause
26  // a resume.
27  req.pause();
28  req.on('data', function() {});
29
30  // Start sending the response.
31  res.flushHeaders();
32}));
33
34server.listen(0, mustCall(function() {
35  const req = http.request({
36    method: 'POST',
37    port: server.address().port
38  });
39
40  // Send the http request without waiting
41  // for the body.
42  req.flushHeaders();
43
44  req.on('response', mustCall(function(res) {
45    // Pipe the body as soon as we get the headers of the
46    // response back.
47    fs.createReadStream(__filename).pipe(req);
48
49    res.resume();
50
51    // On some platforms the `'end'` event might not be emitted because the
52    // socket could be destroyed by the other peer while data is still being
53    // sent. In this case the 'aborted'` event is emitted instead of `'end'`.
54    // `'close'` is used here because it is always emitted and does not
55    // invalidate the test.
56    res.on('close', function() {
57      server.close();
58    });
59  }));
60
61  req.on('error', function() {
62    // An error can happen if there is some data still
63    // being sent, as the other side is calling .destroy()
64    // this is safe to ignore.
65  });
66}));
67