• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const fixtures = require('../../test/common/fixtures');
4const https = require('https');
5
6const options = {
7  key: fixtures.readKey('rsa_private.pem'),
8  cert: fixtures.readKey('rsa_cert.crt')
9};
10
11const storedBytes = Object.create(null);
12const storedBuffer = Object.create(null);
13
14module.exports = https.createServer(options, (req, res) => {
15  // URL format: /<type>/<length>/<chunks>/chunkedEnc
16  const params = req.url.split('/');
17  const command = params[1];
18  let body = '';
19  const arg = params[2];
20  const n_chunks = parseInt(params[3], 10);
21  const chunkedEnc = params.length >= 5 && params[4] === '0' ? false : true;
22  let status = 200;
23
24  let n, i;
25  if (command === 'bytes') {
26    n = ~~arg;
27    if (n <= 0)
28      throw new Error('bytes called with n <= 0');
29    if (storedBytes[n] === undefined) {
30      storedBytes[n] = 'C'.repeat(n);
31    }
32    body = storedBytes[n];
33  } else if (command === 'buffer') {
34    n = ~~arg;
35    if (n <= 0)
36      throw new Error('buffer called with n <= 0');
37    if (storedBuffer[n] === undefined) {
38      storedBuffer[n] = Buffer.allocUnsafe(n);
39      for (i = 0; i < n; i++) {
40        storedBuffer[n][i] = 'C'.charCodeAt(0);
41      }
42    }
43    body = storedBuffer[n];
44  } else {
45    status = 404;
46    body = 'not found\n';
47  }
48
49  // example: https://localhost:port/bytes/512/4
50  // sends a 512 byte body in 4 chunks of 128 bytes
51  const len = body.length;
52  if (chunkedEnc) {
53    res.writeHead(status, {
54      'Content-Type': 'text/plain',
55      'Transfer-Encoding': 'chunked'
56    });
57  } else {
58    res.writeHead(status, {
59      'Content-Type': 'text/plain',
60      'Content-Length': len.toString()
61    });
62  }
63  // send body in chunks
64  if (n_chunks > 1) {
65    const step = Math.floor(len / n_chunks) || 1;
66    for (i = 0, n = (n_chunks - 1); i < n; ++i)
67      res.write(body.slice(i * step, i * step + step));
68    res.end(body.slice((n_chunks - 1) * step));
69  } else {
70    res.end(body);
71  }
72});
73