11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ciconst common = require('../common');
41cb0ef41Sopenharmony_ciconst assert = require('assert');
51cb0ef41Sopenharmony_ciconst http = require('http');
61cb0ef41Sopenharmony_ciconst helloWorld = 'Hello World!';
71cb0ef41Sopenharmony_ciconst helloAgainLater = 'Hello again later!';
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_cilet next = null;
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ciconst server = http.createServer((req, res) => {
121cb0ef41Sopenharmony_ci  res.writeHead(200, {
131cb0ef41Sopenharmony_ci    'Content-Length': `${(helloWorld.length + helloAgainLater.length)}`
141cb0ef41Sopenharmony_ci  });
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_ci  // We need to make sure the data is flushed
171cb0ef41Sopenharmony_ci  // before writing again
181cb0ef41Sopenharmony_ci  next = () => {
191cb0ef41Sopenharmony_ci    res.end(helloAgainLater);
201cb0ef41Sopenharmony_ci    next = () => { };
211cb0ef41Sopenharmony_ci  };
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_ci  res.write(helloWorld);
241cb0ef41Sopenharmony_ci}).listen(0, function() {
251cb0ef41Sopenharmony_ci  const opts = {
261cb0ef41Sopenharmony_ci    hostname: 'localhost',
271cb0ef41Sopenharmony_ci    port: server.address().port,
281cb0ef41Sopenharmony_ci    path: '/'
291cb0ef41Sopenharmony_ci  };
301cb0ef41Sopenharmony_ci
311cb0ef41Sopenharmony_ci  const expectedData = [helloWorld, helloAgainLater];
321cb0ef41Sopenharmony_ci  const expectedRead = [helloWorld, null, helloAgainLater, null, null];
331cb0ef41Sopenharmony_ci
341cb0ef41Sopenharmony_ci  const req = http.request(opts, (res) => {
351cb0ef41Sopenharmony_ci    res.on('error', common.mustNotCall());
361cb0ef41Sopenharmony_ci
371cb0ef41Sopenharmony_ci    res.on('readable', common.mustCall(() => {
381cb0ef41Sopenharmony_ci      let data;
391cb0ef41Sopenharmony_ci
401cb0ef41Sopenharmony_ci      do {
411cb0ef41Sopenharmony_ci        data = res.read();
421cb0ef41Sopenharmony_ci        assert.strictEqual(data, expectedRead.shift());
431cb0ef41Sopenharmony_ci        next();
441cb0ef41Sopenharmony_ci      } while (data !== null);
451cb0ef41Sopenharmony_ci    }, 3));
461cb0ef41Sopenharmony_ci
471cb0ef41Sopenharmony_ci    res.setEncoding('utf8');
481cb0ef41Sopenharmony_ci    res.on('data', common.mustCall((data) => {
491cb0ef41Sopenharmony_ci      assert.strictEqual(data, expectedData.shift());
501cb0ef41Sopenharmony_ci    }, 2));
511cb0ef41Sopenharmony_ci
521cb0ef41Sopenharmony_ci    res.on('end', common.mustCall(() => {
531cb0ef41Sopenharmony_ci      server.close();
541cb0ef41Sopenharmony_ci    }));
551cb0ef41Sopenharmony_ci  });
561cb0ef41Sopenharmony_ci
571cb0ef41Sopenharmony_ci  req.end();
581cb0ef41Sopenharmony_ci});
59