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);

2 Responses to “Serve static files with Node.js”

  1. Steve Gardner May 28, 2015 at 6:35 pm #

    Thanks for this example, Richard! Why did you declare

    var f = lookup

    rather than using

    lookup

    in your function calls? Is it faster?

    • Rick June 4, 2015 at 7:14 pm #

      Oh, it’s been more than two years since I wrote this. Also it’s been a while since I played with NodeJS, not much action in the real world.

      I don’t know the answer, honestly I can’t remember. Feel free to play with it and if you find it performs differently, let us know! 😉

Leave a Reply

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