Tag Archives: Express


Serving throttled static files in NodeJS Express

Curren­tly I’m not only PHP deve­lo­per, but rather <put some random technology> deve­lo­per. I need to have at least basic under­stan­ding about what’s going on in Node Express, Java Spring and Angu­lar JS. That’s why I’ll talk about NodeJS a bit today.

Serving static files on Express is rather trivial. Under the hood express.static uses serve-static module and that’s it. There are plenty of confi­gu­ra­tion options. Usually it’s enough to have file serving up’n’running smoothly. But I wanted to take control over file stre­aming even further.

Imagine user who did not pay on time for your service and you need to punish him a little by setting him a down­load limit to 300 KB/s max. ;-) I know I could use limit_rate in Nginx. But it’s pretty static. There are Lua scrip­ting possi­bi­li­ties to coun­ter that, but c’mon, I’m too old for that stuff ;-)

We’re going to use advan­ced throt­tle npm library. Basi­cally it utili­zes Node stream Trans­form with extra passth­ro­ugh magic. Code is pretty simple, but it took me a while to make it working with serve-static.

Ecma­Script 6 consts are well suppor­ted in Node 6 and 7. If you’re using Node < 6 then replace consts to vars.

The nice thing is we have no bloc­king here. Promise ;-)