Static folder with nodejs and express

var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.use(app.static('public'));
server.listen(3000);


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

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

I was just trying to fire up very small work project but I got stuck when it came to static content. I have checked other similar threads but I can't find out why it won't work for me. I just get this error:

server.use(app.static('public'));
                     ^
TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'static'

I guess I'm doing something wrong but I can't really think out what. Maybe I should go to bed soon enough :)

The API as of express 3 is you need the plain express module to be separate from your app instance.

var express = require('express'); //do NOT invoke the function here
var app = express(); //DO invoke it here to get app
app.use(express.static(__dirname + '/public'));

The problem is that you need to use express.static(), not app.static(). In your example, app was effectively created by

var express = require('express');
var app = express();

However you shortened it to

var app = require('express')();

Because you did this you don't have any reference to the base express object other than by using require('express') again, and this is the reference you need to use static.

You can fix this two ways.

1) Change your beginning code to

var express = require('express')
    , app = express()
    , server = require('http').createServer(app)
    , io = require('socket.io').listen(server);

and your configure to

app.use(express.static(path.join(__dirname, 'public')));

2) Simply change the configure to

app.use(require('express').static(path.join(__dirname, 'public')));

However you'd have to do this whenever you reference Express. Note that I haven't tried this option, but I'm assuming it'll work.

I would definately recommend option one. Also, you should probably create the server after you do the configuration and such for the app.