Serving static files
Anyone using Node to create a web server will need to respond intelligently to HTTP requests. An HTTP request to a web server for a resource expects some sort of response. A basic file static file server might look like this:
http.createServer((request, response) => { if(request.method !== "GET") { return response.end("Simple File Server only does GET"); } fs .createReadStream(__dirname + request.url) .pipe(response); }).listen(8000);
This server services GET requests on port 8000
, expecting to find a local file at a relative path equivalent to the URL path segment. We see how easy Node makes it for us to stream local file data, simply piping a ReadableStream
into a WritableStream
representing a client socket connection. This is an enormous amount of functionality to be safely implemented in a handful of lines.
Eventually, a great deal more will be added, such as handling routines for standard HTTP methods, handling errors and malformed requests...