Node(22) Downloading

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( 200, {
		'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.length - 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 an abort scenario
        download.aborted = true;
    };
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章