4

I want to serve html files from a folder if they exist, otherwise fallback to the dynamic app.

currently I use something like:

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

server.listen(4444);

app.use("/", express.static(__dirname + '/../WebContent/index.html'));
app.use("/styles", express.static(__dirname + '/../WebContent/styles'));
app.use("/script", express.static(__dirname + '/../WebContent/script'));

//here I would like to define a rule like this:
//app.use("*.html", express.static(__dirname + '/../WebContent/*html'));

How can I achieve this?

Some tutorials use a module called connect. If it's the most elegant solution to my problem, how can I integrate connect to my current code?

Coyote
  • 2,454
  • 26
  • 47

2 Answers2

4

You don't have to do anything special.

i'm assuming the WebContent folder is in the root.

And if all your static content are in the same base folder like you've shown, you don't have to specify it multiple times.

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

if you have a file called file.html in the WebContent folder you can now access it via the url i.e. localhost:4444/file.html

scartag
  • 17,548
  • 3
  • 48
  • 52
  • No, `WebContent` is not in the root folder... Is that why It doesn't work? – Coyote Jan 02 '13 at 16:14
  • @Coyote I'd guess so. because __dirname refers to the root of the web app .. so its hard to tell what __dirname +/../WebContent is resolving to. – scartag Jan 02 '13 at 16:15
  • 1
    Thank you! using `app.use(express.static(path.normalize(path.join(__dirname,'../WebContent'))));` it works perfectly! – Coyote Jan 02 '13 at 16:18
2

You are using a lot of boilerplate. It is easier using routes. Here is an example:

var routes = require('./routes');

app.configure(function () {
    ...
    app.use(express['static'](path.join(__dirname, '/../WebContent')));
    app.use(app.router);
});

// Routes
app.get('/', routes.index);

routes/index.js:

exports.index = function (req, res) {
   res.render('index');
};

Rendering your webapp root outside your project root is very strange. Feels like bad practice. Is this necessary?

asgoth
  • 35,552
  • 12
  • 89
  • 98
  • It's a bit of a collage. `../WebContent` comes from another project and unfortunately I also absolutely need `socket.io` for this project. – Coyote Jan 02 '13 at 16:27
  • What is the advantage of routes over the usual express use/get way? – Coyote Jan 02 '13 at 17:40