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

Podobne wpisy:

  1. Symfony2 compi­ler pass with tags and custom attributes
  2. Wali­duj z Harrym Potterem
  3. PDO poprzez Depen­dency Injec­tion Conta­iner [cz. 2/2]
  4. Mój pierw­szy raz… z Javą :-)

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany.

Możesz użyć następujących tagów oraz atrybutów HTML-a: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <p> <pre lang="" line="" escaped=""> <q cite=""> <strike> <strong>