Reputation: 6182
Right now, any static html will get server as is (about.html, work.html, etc) using
app.use express.static("#{__dirname}/app")
How do I tell it to return the same file with just "about"?
Upvotes: 1
Views: 1504
Reputation: 1635
You could use Express' res.sendfile
. A basic example:
app.get('/:file', function (req, res) { var file = req.params.file; res.sendfile('app/' + file + '.html'); });
Upvotes: 2
Reputation: 144912
express.static
actually comes from Connect, on which Express is built. If you look at the source of the static middleware, you'll see that it's relatively simple, since the real logic has been abstracted out to the send module.
The baked-in static middleware cannot do what you're trying to accomplish, but it would be simple enough to tweak it into your own:
var send = require('./node_modules/express/node_modules/send') // grab the npm-installed send module that comes with express
, utils = require('.node_modules/express/node_modules/connect/lib/utils') // ...and connect's utils
, parse = utils.parseUrl
, url = require('url');
function customStatic(root, options){
options = options || {};
// root required
if (!root) throw new Error('static() root path required');
// note: I've stripped out directory redirection
// (ie, redirecting from /somefolder to /somefolder/)
// because appending an extension logically makes that code unreachable
return function(req, res, next) {
if ('GET' != req.method && 'HEAD' != req.method) return next();
var path = parse(req).pathname
, filename = pathname.substr(pathname.lastIndexOf('/')); // the part of the URL after the last slash, excluding the query string
// and finally, the reason we're here: if the filename has no extension, append one
if (options.defaultExtension && filename.indexOf('.') == -1) path += '.' + options.defaultExtension;
var pause = utils.pause(req);
function resume() {
next();
pause.resume();
}
function error(err) {
if (404 == err.status) return resume();
next(err);
}
send(req, path)
.maxage(options.maxAge || 0)
.root(root)
.index(options.index || 'index.html')
.hidden(options.hidden)
.on('error', error)
.pipe(res);
};
};
Then use it just like the Connect's static module:
app.use(customStatic(__dirname + '/app', { defaultExtension: 'html' }));
Upvotes: 3