Performance: express.static middleware
This affects how quickly static files like images, CSS, and JavaScript are served to the browser, impacting page load speed.
app.use('/static', express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
if (req.url.startsWith('/static/')) {
const filePath = path.join(__dirname, 'public', req.url.replace('/static/', ''));
fs.readFile(filePath, (err, data) => {
if (err) return next();
res.send(data);
});
} else {
next();
}
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual file read per request | N/A | N/A | Increases server response delay | [X] Bad |
| express.static middleware | N/A | N/A | Fast response, enables browser caching | [OK] Good |
express.static middleware in an Express app?express.staticexpress.static middleware serves these files directly from a folder, making them accessible via URLs.express.static to serve files from a folder named public?app.use() with the middleware function inside.express.static function takes the folder name as a string and returns middleware, so app.use(express.static('public')) is correct.app.use('/assets', express.static('public'));
// Client requests: GET /assets/image.pngapp.use(express.static('public'));
app.use('/static', express.static('public'));/static/style.css, what happens?public at root URL and uploads at /files. Which code correctly sets this up?app.use(express.static('public')) serves files from 'public' at root URL.app.use('/files', express.static('uploads')) serves files from 'uploads' folder under '/files' URL.Pass the test and this pattern moves unknown