Node (downloading)

Source: Internet
Author: User

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





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.