This is tangential, but I noticed you're using synchronous APIs here. You
almost certainly should be using the async APIs. Also you're attaching
another 'close' handler on every interval.
On Thursday, January 30, 2014 7:27:15 PM UTC-5, Rodrive wrote:
>
> Hi, first of all sorry for my english.
>
> I have to limit the download speed for a file and only the download of the
> file.
> I explain what i mean. I do not want to limit the bandwidth access to my
> website but only the download speed for a file and only this download.
> If I limit the bandwith for a specific user to limit the download speed,
> all the access to my website will be restrained.
>
> I didnt find much informations to do this. I did this (that is working,
> limit the average to 300KB/sec), but i dont know if it is a good way or not
> :
>
> var fs = require('fs');
>>
>> var path = require('path');
>>
>> var filesize = require('filesize');
>>
>> var http = require('http');
>>
>>
>>> function onRequest(request, response){
>>
>> var filepath = './public/test.mp3';
>>
>> var file = {
>>
>> path: filepath,
>>
>> name: path.basename(filepath),
>>
>> size: (fs.statSync(filepath)).size
>>
>> };
>>
>> console.log('file :' + file.name, 'size :' + filesize(file.size));
>>
>>
>>> fs.open(file.path, 'r', function (err, fd){
>>
>> response.writeHead(200,{
>>
>> 'Content-Type': 'application/octet-stream',
>>
>> 'Content-Length': file.size,
>>
>> 'Content-Disposition': "attachment;filename="+file.name
>>
>> });
>>
>>
>>>
>>> var buff = new Buffer(4096);
>>
>> var position = 0;
>>
>> var id = setInterval(function (){
>>
>> var quota = 307200; //Byte par seconde
>>
>>
>>> request.on('close', function(){
>>
>> console.log(truc);
>>
>> clearInterval(id);
>>
>> response.end();
>>
>> fs.close(fd);
>>
>> quota = 0;
>>
>> });
>>
>>
>>> while (quota > 0){
>>
>> var bytesRead = fs.readSync(fd, buff, 0, buff.length,
>>> position);
>>
>> response.write(buff);
>>
>> position += bytesRead;
>>
>> quota -= bytesRead;
>>
>>
>>> if (bytesRead < buff.length){
>>
>> console.log('over');
>>
>> clearInterval(id);
>>
>> response.end();
>>
>> fs.close(fd);
>>
>> break;
>>
>> }
>>
>> }
>>
>> }, 1000);
>>
>> });
>>
>> }
>>
>>
--
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en
---
You received this message because you are subscribed to the Google Groups
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.