Serve static files with Node.js

Don’t forget to checkout How to Install Node.js and hotnode.

With Node.js one thing you want to do at some point is load an static resource such as an .html file with some CSS or JavaScript.

index.html

This file could also have some CSS styles or JavaScript functions (even retrieving them from an other styles.css or scripts.js files).

 <html>
   <head>
     <title>This is my Index.html</title>
   </head>
   <body>
     Hello World!
   </body>
 </html>

server.js

It’s easy to get overwhelmed with this bunch of code.

I’m not going to break it down but if you look at it I’m sure you won’t have any problems understanding it.

var http = require('http');
var path = require('path');
var fs = require('fs');

var mimeTypes = {
 '.js' : 'text/javascript',
 '.html': 'text/html',
 '.css' : 'text/css'
};

 http.createServer(function (request, response) {

     var lookup = path.basename(decodeURI(request.url)) || 'index.html', f = lookup;
     
     fs.exists(f, function (exists) {
     
       if (exists) {
           
           fs.readFile(f, function(err, data) {
               
               if (err) {
               
                response.writeHead(500); response.end('Server Error!');
               
                return;
              }
                   
           var headers={'Content-type': mimeTypes[path.extname(lookup)]}; response.writeHead(200, headers);
           
           response.end(data);
           
        });
       
        return;
     }   
   
    response.writeHead(404);
   
    response.end();
   
  });
 
}).listen(8080);
No comments yet, leave yours!

Leave a Reply

Add <code> Some Code </code> by using this tags.