So the general idea of a node static server is that I have some plain old static files in a public folder and I just want to server them up over the http protocol on my local computer. Maybe what I am working on will be deployed to a site elsewhere at a latter time, and for whatever the reason I just need to serve it up on my computer via something other than the file protocol.
So I just need a script that I can call from node like this.
And the script will serve static files that I have in a public folder localed at the current working path where I have the script. I could also install the script globally, but for now I just want to make a script that is closely tiles to the project folder.
So here is a basic node static file server file that I worked out. Here I just placed this code in a file called server1.js in the root path of the project folder. In the project folder I also have a public folder and in there I have a index html file at the root of the project folder.
I use the file system module of nodejs to check the stats of a file that is being requested. If the file is there then it will be sent to the client, if the file is not there then a 500 status will result and the request will be ended. If the file is there the file system module read file method will be used to read and send the contents of the file.
So of course this solution just handles GET requests which works fine in most situations. In the event that a path is given such as ‘/‘ then ‘/index.html’ is assumed. In addition in the event of any kind of error the request is just ended, and I do not serve any kind of 404 page.