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.


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

     <title>This is my Index.html</title>
     Hello World!
 </html>Code language: HTML, XML (xml)


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!');
		   var headers={'Content-type': mimeTypes[path.extname(lookup)]}; response.writeHead(200, headers);
}).listen(8080);Code language: JavaScript (javascript)


  1. Steve Gardner says:

    Thanks for this example, Richard! Why did you declare

    var f = lookupCode language: JavaScript (javascript)

    rather than using


    in your function calls? Is it faster?

    1. Rick says:

      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

Your email address will not be published. Required fields are marked *