Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Serving Static Files with Express.js

1. Introduction

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Serving static files is a fundamental aspect of web development. In this lesson, we will explore how to serve static files efficiently using Express.js.

2. Setup

To get started, ensure you have Node.js and npm installed. Then, create a new directory for your project and install Express.js:

mkdir express-static-example
cd express-static-example
npm init -y
npm install express

3. Static Files

Static files are files that are served to the client exactly as they are stored on the server. Common types of static files include HTML, CSS, JavaScript, images, and fonts.

3.1 Creating a Static Directory

Create a new folder named public in your project directory. This folder will contain all your static files.

mkdir public
touch public/index.html public/style.css

3.2 Example Static File

In public/index.html, add the following HTML content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Static File Example</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is a static HTML file served by Express.js.</p>
</body>
</html>

4. Using Middleware

Express.js provides a built-in middleware function called express.static to serve static files. Here’s how to set it up:

const express = require('express');
const app = express();
const path = require('path');

// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

5. Best Practices

Note: Always serve static files in a dedicated directory to keep your application organized.
  • Use express.static for efficient file serving.
  • Cache static files by setting appropriate cache-control headers.
  • Minimize file sizes using compression techniques.
  • Use a CDN for serving static assets in production environments.

6. FAQ

Can I serve files from multiple directories?

Yes, you can call app.use() multiple times to serve static files from different directories.

What types of files can I serve?

You can serve any type of file, including HTML, CSS, JavaScript, images, and more.

How do I set cache-control headers?

You can set cache-control headers using middleware or by passing options to express.static.