Reputation: 5
i'm new to node.js, so please be indulgently.
I'm just playing around with node.js and the express-module. I had an idea how to deal with browser-requests and now i have a simple question:
Is this a good idea/practice or is there a better solution to handle that?
var http = require('http');
var express = require('express');
var fs = require('fs');
var app = express();
http.createServer(app).listen(80);
app.get('/*',function(req,res,next){
fs.exists(__dirname + req.url, function (exists) {
if(exists)
{
console.log('Sending ' + __dirname + req.url + "...");
res.sendfile(__dirname + req.url);
}
else
{
console.log(__dirname + req.url + " not found!");
res.send('Sorry, page not found.',404);
}
});
});
Upvotes: 0
Views: 314
Reputation: 387815
Express is based on Connect and as such supports its middleware. And there is a perfect middleware for your situation: static file serving.
app.use(express.static(__dirname + '/public'));
This will serve all files within the /public
directory as static files available from the root directory. For routes which are not handled separately and for which no file exists, a 404 error is returned.
Btw. you want to put the listen
-call to the end.
Upvotes: 1