Gregory Wullimann Gregory Wullimann - 3 months ago 25
Node.js Question

NodeJS - Serve file with throttled speed

I'm quite new to NodeJS and trying different stuff.

What I was able to do is to download a file going using the following code:

app.get('/download', function(req, res){


var file = 'public/songs/myfile.mp3';

var filename = path.basename(file);
var mimetype = mime.lookup(file);

res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
res.setHeader('Content-Length', file.length);

var filestream = fs.createReadStream(file);

filestream.pipe(res);
});


This works well, now what I'm trying to achive is see if it's possible to throttle the download speed. Like if someone tries to download the file it will download at max 1 Mbps (for example).

I've tried to use this code: https://gist.github.com/4poc/1454516

When I load the page it seems to load indefinetly, but I think that the problem is

filestream.pipe(limitStream);


Since that no response is given.

How can I implement what I would like to do? Or how I can fix the code I tried to use?

Answer

The req and res objects are streams, so you can pipe on the response:

var filestream = fs.createReadStream(file);

filestream.pipe(limitStream).pipe(res);

fwiw: every time you call pipe() you get back a new stream. The above is the same as this:

var filestream = fs.createReadStream(file);

var throttleStream = filestream.pipe(limitStream);

throttleStream.pipe(res);

This is important to understand because it's tempting to do this, but it won't do what you expect:

var filestream = fs.createReadStream(file);

filestream.pipe(limitStream);

filestream.pipe(res);