Node(22) Downloading

本文探讨了如何使用Node.js实现HTTP下载时的限速功能,通过引入Throttle算法,确保数据传输速度稳定在指定的每秒千比特(kbps)。详细介绍了从读取文件到数据传输的全过程,包括如何创建读取流、限制数据发送速率以及如何在关闭响应时停止数据传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    };
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值