Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Created March 1, 2018 16:55
Show Gist options
  • Save mathieuancelin/c0079c60cd8cb2a0fb2fddf6672da820 to your computer and use it in GitHub Desktop.
Save mathieuancelin/c0079c60cd8cb2a0fb2fddf6672da820 to your computer and use it in GitHub Desktop.
const http = require('http');
const url = require('url');
const faker = require('faker');
const bytes = require('bytes');
const _ = require('lodash');
const port = process.env.PORT || process.argv[2] || 8080;
const cache = {};
const server = http.createServer((req, res) => {
const query = url.parse(req.url, true).query;
const size = bytes.parse(String(query.size || '1KB'));
const latency = query.latency ? parseInt(query.latency, 10) : 200;
const time = query.time ? parseInt(query.time, 10) : 100;
const mb = 1048576;
const nbrOfChunks = size > (10 * mb) ? parseInt((size / mb).toFixed(0), 10) : 10;
const timeout = parseInt((time / nbrOfChunks).toFixed(0), 10);
const chunkSize = parseInt((size / nbrOfChunks).toFixed(0), 10);
const range = _.range(nbrOfChunks).map(() => chunkSize + 1);
res.writeHead(200, {
'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked'
});
function pushChunk() {
const item = range.pop();
if (item) {
let chunk = cache[`chunk-${chunkSize}`];
if (!chunk) {
chunk = faker.random.alphaNumeric(chunkSize);
cache[`chunk-${chunkSize}`] = chunk;
}
res.write(chunk, 'utf-8');
setTimeout(() => pushChunk(), timeout);
} else {
res.end('');
}
}
setTimeout(() => pushChunk(), latency);
});
server.listen(port, () => {
console.log(`Benchmark server started on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment