Examples of serving static files with HTTP using Node.js
on five levels of abstraction - from express.static
to directly using the net
module with raw TCP sockets.
It was written for the answer on Stack Overflow:
Read this answer for some background and better explanation.
Other related answers on Stack Overflow:
- Failed to load resource from same directory when redirecting Javascript
- onload js call not working with node
- Sending whole folder content to client with express
- Loading partials fails on the server JS
- Node JS not serving the static image
Every example serves the same files from the public
directory and supports the minumum functionality of:
- MIME types for most common files
- must serve HTML, JS, CSS, plain text and images
- serves
index.html
as a default directory index - responds with error codes for missing files
- no path traversal vulnerabilities
- no race conditions while reading files
Every version is tested with Travis on Node versions 4, 5, 6 and 7. See test results.
All examples:
This version uses the express.static
built-in middleware of the express
module.
This example has the most functionality and the least amount of code.
This version uses the express
module but without the express.static
middleware. Serving static files is implemented as a single route handler using streams.
This example has simple path traversal countermeasures and supports a limited set of most common MIME types.
This version uses the connect
module which is a one level of abstraction lower than express
.
This example has similar functionality to the express
version but using slightly lower-lever APIs.
This version uses the http
module which is the lowest-level API for HTTP in Node.
This example has similar functionality to the connect
version but using even more lower-level APIs.
This version uses the net
module which is the lowest-level API for TCP sockets in Node.
This example has some of the functionality of the http
version but the minimal and incomplete HTTP protocol has been implemented from scratch. Since it doesn't support chunked encoding it loads the files into memory before serving them to know the size before sending a response because statting the files and then loading would introduce a race condition.
Download the files using git:
git clone git@github.com:rsp/node-static-http-servers.git
# or:
git clone https://github.com/rsp/node-static-http-servers.git
Or download a ZIP file:
wget https://github.com/rsp/node-static-http-servers/archive/master.zip
tar xzvf master.zip
Install dependencies:
npm install
Running tests:
npm test
Running individual servers:
node net.js
node http.js
node connect.js
node express.js
node estatic.js
For any bug reports or feature requests please post an issue on GitHub.
MIT License (Expat). See LICENSE.md for details.