Instantly share code, notes, and snippets.

What would you like to do?
express.static middleware must be added before any routes are added to the project, which is potentially confusing when constructing reusable modules to be added to projects as needed. I wish app.use() behaved as just another route for precedence purposes
// HOPED-FOR BEHAVIOR: both /cats.txt AND /cats/cats.txt say: Cats Static
// ACTUAL BEHAVIOR: /cats.txt says Cats Static, but /cats/cats.txt says: Main Wildcard
var express = require('express');
var fs = require('fs');
var app = express();
// Adding the static middleware at the beginning means it wins out over any routes present
// (but only interferes if the file exists)
app.use(express.static(__dirname + '/static'));
if (!fs.existsSync('./static')) {
fs.writeFileSync('./static/cats.txt', 'Cats Static');
app.get('/', function(req, res) {
res.send('Main Home');
// If this statement is called way up top before any routes are added,
// /cats/cats.txt works as expected
app.use('/cats', express.static(__dirname + '/static'));
// If this wildcard route is removed, /cats/cats.txt works as expected
app.get('/*', function(req, res) {
res.send('Main Wildcard');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment