Skip to content

Instantly share code, notes, and snippets.

@panta82
Created March 8, 2016 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panta82/c768303e10796cf47d41 to your computer and use it in GitHub Desktop.
Save panta82/c768303e10796cf47d41 to your computer and use it in GitHub Desktop.
Copy file sloooooowly, so that we can test network related stuff
#!/usr/bin/env node
var fs = require('fs');
var util = require('util');
var DEFAULT_BPS = 10 * 1000; // 10 kb / sec
var source = process.argv[2];
if (!source) {
return usage(1);
}
var dest = process.argv[3];
if (!dest) {
return usage(1);
}
var PARAMS = {
bps: Number(process.argv[4]) || DEFAULT_BPS
};
PARAMS.chunkSize = PARAMS.bps / 10;
PARAMS.highWaterMark = PARAMS.chunkSize * 6;
PARAMS.lowWaterMark = PARAMS.chunkSize * 3;
var STATS = {
read: 0,
written: 0
};
var buffer = new Buffer(0),
finishedReading = false;
var rs = fs.createReadStream(source, {});
var ws = fs.createWriteStream(dest, {
mode: 0664
});
rs.on('data', function (data) {
STATS.read += data.length;
buffer = Buffer.concat([buffer, data]);
if (buffer.length > PARAMS.highWaterMark) {
rs.pause();
}
});
rs.on('end', function () {
console.log('Done reading');
finishedReading = true;
});
var flushInterval = setInterval(flush, 100);
var reportingInterval = setInterval(report, 1000);
function usage(exitCode) {
console.log(util.format('Usage: %s %s <source> <dest> [bps]', process.argv[0], process.argv[1]));
process.exit(exitCode >= 0 ? exitCode : 0);
}
function flush() {
var chunk = buffer.slice(0, PARAMS.chunkSize);
if (chunk.length > 0) {
ws.write(chunk);
STATS.written += chunk.length;
buffer = buffer.slice(chunk.length);
if (buffer.length < PARAMS.lowWaterMark) {
rs.resume();
}
}
else if (finishedReading) {
ws.end();
clearInterval(flushInterval);
clearInterval(reportingInterval);
console.log('Done writing');
}
}
function report() {
console.log(util.format('Read: %s | Written: %s | Buffered: %s', STATS.read, STATS.written, buffer.length));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment