Gregory Wullimann Gregory Wullimann - 1 year ago 84
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);


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:

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


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 Source

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

var filestream = fs.createReadStream(file);


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


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