Basic webserver with node.js and express for serving html file and assets

Following code worked for me.

var express = require('express'),
  app = express(),
  http = require('http'),
  httpServer = http.Server(app);

app.use(express.static(__dirname + '/folder_containing_assets_OR_scripts'));

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});
app.listen(3000);

this loads page with assets


You could use a solution like this in node.js (link no longer works), as I've blogged about before.

The summarise, install connect with npm install connect.

Then paste this code into a file called server.js in the same folder as your HTML/CSS/JS files.

var util = require('util'),
    connect = require('connect'),
    port = 1337;

connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.');

Now navigate to that folder in your terminal and run node server.js, this will give you a temporary web server at http://localhost:1337


I came across this because I have a similar situation. I don't need or like templates. Anything you put in the public/ directory under express gets served as static content (Just like Apache). So I placed my index.html there and used sendfile to handle requests with no file (eg: GET http://mysite/):

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});