Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Serving Static Files
tutorial

Serving Static Files

HTML pages are just the beginning. Real websites also need CSS for styling, JavaScript for interactivity, images, and other assets. These are called **static files** because they don't change based on the request – they're the same for everyone.

What are Static Files?

Static files are files that are served directly to the client without any server-side processing. Common static files include:
  • CSS stylesheets
  • Client-side JavaScript
  • Images (PNG, JPG, SVG)
  • Fonts
  • PDFs and other downloads

Think of static files as the ingredients in your pantry – they're always there, and you just take them out when needed, no cooking required.

Project Structure with Static Files
my-server/
├── server.js
├── views/
│ ├── index.html
│ └── about.html
├── public/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── script.js
│ └── images/
│ └── logo.png

Sample CSS File (public/css/style.css)
body {
  font-family: Arial, sans-serif;
  margin: 40px;
  background-color: #f0f0f0;
}
h1 {
  color: #333;
}

Sample HTML Linking Static Files (views/index.html)
<!DOCTYPE html>
<html>
<head>
  <title>Home Page</title>
  <link rel="stylesheet" href="/css/style.css">
</head>
<body>
  <h1>Welcome</h1>
  <img src="/images/logo.png" alt="Logo">
  <script src="/js/script.js"></script>
</body>
</html>

Serving Static Files in Node.js

We'll extend our server to handle requests for static files. The idea is simple: if the requested URL starts with `/css/`, `/js/`, or `/images/`, we serve the corresponding file from the `public` folder.
const http = require('http');
const fs = require('fs');
const path = require('path');

function getContentType(filePath) {
  const extname = path.extname(filePath);
  switch (extname) {
    case '.css': return 'text/css';
    case '.js': return 'application/javascript';
    case '.png': return 'image/png';
    case '.jpg':
    case '.jpeg': return 'image/jpeg';
    case '.gif': return 'image/gif';
    case '.svg': return 'image/svg+xml';
    case '.json': return 'application/json';
    default: return 'text/plain';
  }
}

function serveStaticFile(res, filePath) {
  fs.readFile(filePath, (err, content) => {
    if (err) {
      res.writeHead(404);
      res.end('File not found');
    } else {
      const contentType = getContentType(filePath);
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content);
    }
  });
}

const server = http.createServer((req, res) => {
  <!-- Serve static files if URL starts with /css/, /js/, /images/ -->
  if (req.url.startsWith('/css/') || req.url.startsWith('/js/') || req.url.startsWith('/images/')) {
    const filePath = path.join(__dirname, 'public', req.url);
    serveStaticFile(res, filePath);
  } else if (req.url === '/') {
    const filePath = path.join(__dirname, 'views', 'index.html');
    serveStaticFile(res, filePath);
  } else if (req.url === '/about') {
    const filePath = path.join(__dirname, 'views', 'about.html');
    serveStaticFile(res, filePath);
  } else {
    const filePath = path.join(__dirname, 'views', '404.html');
    serveStaticFile(res, filePath);
  }
});

server.listen(3000);

Important Points
  • We determine the correct MIME type based on file extension using `getContentType()`.
  • We serve static files from the `public` folder, preserving the URL structure.
  • We reuse the same `serveStaticFile` function for both HTML and static files.

Two Minute Drill

  • Static files include CSS, JavaScript, images, and other assets.
  • Store them in a dedicated folder (commonly `public`).
  • Determine the correct MIME type based on file extension.
  • Serve them by reading the file and sending with appropriate headers.
  • This approach is the foundation of serving any kind of file.
  • In production, you'd often use a CDN or a more optimized static file server.

Need more clarification?

Drop us an email at career@quipoinfotech.com