Why is it not recommended to serve static files from Node.js?View other answers to this thread
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
Node.js developer. Experimenting with bleeding-edge tech. Irregularly DJ. Hobby drone pilot. Amateur photographer.
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.