Performance: Serving static files
This affects how quickly static assets like images, CSS, and JavaScript files load, impacting page load speed and user experience.
Jump into concepts and practice - no test required
import express from 'express'; const app = express(); app.use(express.static('public')); app.listen(3000);
const http = require('http'); const fs = require('fs'); http.createServer((req, res) => { if (req.url === '/style.css') { fs.readFile('./style.css', (err, data) => { if (err) { res.writeHead(404); res.end('Not found'); return; } res.writeHead(200, {'Content-Type': 'text/css'}); res.end(data); }); } else { res.writeHead(404); res.end('Not found'); } }).listen(3000);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Reading files on every request | N/A | N/A | Delays paint due to slow resource load | [X] Bad |
| Using express.static middleware | N/A | N/A | Fast paint due to quick resource delivery | [OK] Good |
express.static in a Node.js server?express.staticexpress.static.public using Express?app.use(express.static('folderName')) to serve static files.const express = require('express');
const app = express();
app.use(express.static('assets'));
app.listen(3000);assets/logo.png?static folder:const express = require('express');
const app = express();
app.use(express.static.static('static'));
app.listen(3000);express.static.static. The correct call is express.static.public folder but under the URL path prefix /static. Which code correctly achieves this?app.use, then the static middleware.app.use('/static', express.static('public')). Others either misuse paths or methods.