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!


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);
No comments yet, leave yours!

Leave a Reply

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