Serving Static Files
3:40:57 - 3:52:38 Serving Static Files Up to this point, Node has been pushing content to the browser using the write-stream API. Kyle now modifies the node application to serve static HTML files. Kyle also field a few questions about keeping track of useful node modules.a simple little tool, to serve static files if you don't want another big framework for that
npm install node-static
and then in your js file:var node_static = require("node-static");
var static_files = new node_static.Server(__dirname);
__dirname
<- is directory where you app is running from (it's a NodeJS special variable)continued from here: Node as a Webserver
function handleHTTP(req,res) {
if (req.method == "GET") {
if (/^\/\d+(?=$|[\/?#])/.test(req.url)) {
req.addListener("end",function(){
req.url = req.url.replace(/^\/(\d+).*$/,"/$1.html");
static_files.serve(req,res);
});
req.resume();
}
// else...
}
/^\/\d+(?=$|[\/?#])/
will recognise url starting with /, continued by a numeric character and an url separator character e.g. /6 is true but not /fooreq.url = req.url.replace(/^\/(\d+).*$/,"/$1.html");
e.g. will "/6" will be rewritten to "/6.html" (this of course could be done by fancy frameworks)node-static will handle all the mime-type settings and declaration, even gzip
you can even pre-gzip files
audiance question: how to choose libraries to use?- how many stars does it have (how most people judge)
- how many dependencies does it have (less the better of course)
- twitter feeds, javascript weekly
- github issues
- actively maintained
- twitter talk about the module
- open up the code (to see if it's useful)
if something is more than a few lines, then could be worth finding a module for it