Skip to content

Instantly share code, notes, and snippets.

@maxbeatty
Created June 30, 2014 20:56
Show Gist options
  • Save maxbeatty/f0e869e34ffce9095007 to your computer and use it in GitHub Desktop.
Save maxbeatty/f0e869e34ffce9095007 to your computer and use it in GitHub Desktop.
Detecting extensions in Express.js (v3) route
var express = require('express'),
app = express();
app.configure(function() {
app.use(app.router);
app.use(function(req, res, next) { res.send(404); });
});
app.get('/:name', function(req, res, next) {
var re = /\.(csv|pdf)$/,
matches = req.params.name.match(re);
if (matches !== null && matches[1]) {
switch (matches[1]) {
case 'csv':
res.type('text/csv');
break;
case 'pdf':
res.type('application/pdf');
break;
}
}
res.format({
'text/csv': function() {
res.set({
'Content-Disposition': 'attachment; filename="'+ req.params.name + '"'
});
res.send(new Buffer("csvData"));
},
'application/pdf': function() {
// do pdf specific things here
},
json: function() {
// built in support by express for AJAX calls
},
default: function() {
res.send('<h1>'+req.params.name+'</h1>');
}
});
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment