Currently I’m not only PHP developer, but rather
<put some random technology> developer. I need to have at least basic understanding about what’s going on in Node Express, Java Spring and Angular JS. That’s why I’ll talk about NodeJS a bit today.
Serving static files on Express is rather trivial. Under the hood
serve-static module and that’s it. There are plenty of configuration options. Usually it’s enough to have file serving up’n’running smoothly. But I wanted to take control over file streaming 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 download limit to 300 KB/s max. ;-) I know I could use
limit_rate in Nginx. But it’s pretty static. There are Lua scripting possibilities to counter that, but c’mon, I’m too old for that stuff ;-)
We’re going to use advanced throttle npm library. Basically it utilizes Node stream Transform with extra passthrough magic. Code is pretty simple, but it took me a while to make it working with
EcmaScript 6 consts are well supported in Node 6 and 7. If you’re using Node < 6 then replace consts to vars.
The nice thing is we have no blocking here. Promise ;-)