static files with express.js

user124114 picture user124114 · May 3, 2012 · Viewed 357.6k times · Source

I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.

I have

web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));

but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.

I also tried

web_server.use("/", express.static(__dirname + '/index.html'));

but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.

Any ideas?


By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.

Answer

250R picture 250R · May 4, 2012

If you have this setup

/app
   /public/index.html
   /media

Then this should get what you wanted

var express = require('express');
//var server = express.createServer();
// express.createServer()  is deprecated. 
var server = express(); // better instead
server.configure(function(){
  server.use('/media', express.static(__dirname + '/media'));
  server.use(express.static(__dirname + '/public'));
});

server.listen(3000);

The trick is leaving this line as last fallback

  server.use(express.static(__dirname + '/public'));

As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.

For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140