Example with throttle
var http = require (' http ');
var fs = require (' FS ');
var options = {};
Options.file = ' pride.txt ';
Options.filesize = Fs.statsync (options.file). Size;
options.kbps = 32;
Http.createserver (function (request, response) {//download inherite from options var download = object.create (options);
Download.chunks = new Buffer (download.filesize);
Keep track of Beffer position download.bufferoffset = 0;
Response.writeheader ({' Content-length ': options.filesize});
Fs.createreadstream (Options.file). On (' Data ', function (chunk) {chunk.copy (download.chunks, Download.bufferoffset);
Download.bufferoffset + = Chunk.length;
}. Once (' open ', function () {var handleabort = throttle (download, function (send) {response.write (send);
});
Response.on (' Close ', function () {handleabort ();
});
});
}). Listen (9000);
function throttle (download, CB) {var chunkoutsize = download.kbps * 1024, timer = 0; (function loop (bytessent) {var remaiNingoffset;
if (!download.aborted) {settimeout (function () {var bytesout = bytessent + chunkoutsize;
if (Download.bufferoffset > bytesout) {timer = 1000;
CB (Download.chunks.slice (bytessent,bytesout));
Loop (bytesout);
Return } if (Bytesout >= download.chunks.length) {remainingoffset = Download.chunks.lengt
H-bytessent;
CB (Download.chunks.slice (remainingoffset,bytessent));
Return Loop (bytessent);
Continue to loop, wait for enough data},timer);
}} (0));
return function () {//return a function to handle a abort scenario download.aborted = true;
}; }