Why is it not recommended to serve static files from Node.js?

View other answers to this thread
Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more

Denny Trebbin's photo

express.static or koa.send consume cpu time which isn't available for your main app loop until file(s) are sent. In details - express.send cares too much for dynamic stuff like settings response headers, calculating response status, calculating size of files, finding correct mime types, etc, etc, etc. this computing happens on your main app loop but this main loop should be used as much as possible exclusively for your business computations only.

nginx is much better used for serving statics. because it does some clever tricks that can't be done by node.js, like linking mime types semi statically based on file extensions only. It has pre-baked response headers and response status and it has a template for such such responses. nginx not only spends less time for building response headers and status, but also uses os features when available to speed up even further. Additionally nginx runs on different cpu core(s)/thread(s) other than your node.js app.

node.js hint: you always wanna do as less as possible on your main app loop.

I hope this makes any sense.

Show +2 replies
Denny Trebbin's photo

you'r welcome jerry :)

Margaret's photo

Perfect. Completely makes sense. Thanks for the detailed answer Denny!