0
0
Node.jsframework~8 mins

Serving static files in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Serving static files
HIGH IMPACT
This affects how quickly static assets like images, CSS, and JavaScript files load, impacting page load speed and user experience.
Serving static files in a Node.js web server
Node.js
import express from 'express';
const app = express();

app.use(express.static('public'));

app.listen(3000);
Uses built-in static middleware that caches file metadata and streams efficiently, reducing unnecessary disk reads.
📈 Performance GainEfficiently streams files and supports browser caching via ETags/Cache-Control, reducing server load and improving LCP.
Serving static files in a Node.js web server
Node.js
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);
Reads the file from disk on every request, causing slow response and high CPU usage.
📉 Performance CostPerforms disk I/O on every request using the limited libuv thread pool, causing contention, slow responses, and delayed LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Reading files on every requestN/AN/ADelays paint due to slow resource load[X] Bad
Using express.static middlewareN/AN/AFast paint due to quick resource delivery[OK] Good
Rendering Pipeline
Serving static files efficiently reduces the time the browser waits for resources, speeding up style and script application and image display.
Network Request
Resource Loading
Style Calculation
Paint
⚠️ BottleneckNetwork Request and Resource Loading due to slow file reads or lack of caching
Core Web Vital Affected
LCP
This affects how quickly static assets like images, CSS, and JavaScript files load, impacting page load speed and user experience.
Optimization Tips
1Avoid reading static files from disk on every request.
2Use built-in static file middleware with caching and compression.
3Check network timings in DevTools to ensure fast static asset delivery.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a common performance problem when serving static files by reading from disk on every request?
AHigh CPU usage and slow response times
BToo many DOM nodes created
CExcessive CSS selector complexity
DLarge JavaScript bundle size
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, and check the timing for static files like CSS and JS.
What to look for: Look for long 'Waiting (TTFB)' or 'Content Download' times indicating slow static file serving.