Performance: Why serving static files matters
Serving static files efficiently affects page load speed and reduces server processing time.
app.use(express.static(path.join(__dirname, 'public')));app.get('/images/:imageName', (req, res) => { const imagePath = path.join(__dirname, 'images', req.params.imageName); fs.readFile(imagePath, (err, data) => { if (err) { res.status(404).send('Not found'); return; } res.setHeader('Content-Type', 'image/jpeg'); res.send(data); }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual file read per request | N/A | N/A | Increases server response time | [X] Bad |
| Express static middleware | N/A | N/A | Faster resource delivery | [OK] Good |
express.static middleware in an Express app?express.staticpublic in Express?app.use(express.static('folderName')).express.static with app.use.const express = require('express');
const app = express();
app.use(express.static('assets'));
app.listen(3000);http://localhost:3000/image.png where assets/image.png exists?/image.png looks for assets/image.png. Since it exists, Express serves it.static folder:const express = require('express');
const app = express();
app.use(express.static);
app.listen(3000);express.static without parentheses and folder name, so it won't work.public and uploads. Which code correctly serves both folders so files from either can be accessed by URL?app.use(express.static()) multiple times.Pass the test and this pattern moves unknown