Serving Static Files with Express

Hello everyone! In this tutorial, we’ll cover how serving static files with Express.js can streamline your web development

Step 1: Set up your project

First, create a new folder for your project and initialize it with npm npm init. Then, install Express using:

npm install express

Step 2: Create an Express server

Create a file named server.js. This file will hold the Express application logic.

const express = require('express');
const app = express();
const port = 3000;

// Serve static files from the 'public' directory
app.use(express.static('public'));

// Define a simple route
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Step 3: Create a ‘public’ directory

In the same directory as server.js, create a folder named public Place all your static files (like HTML, CSS, images, etc.) in this folder. For example:

  • public/index.html
  • public/style.css
  • public/image.png

Step 4: Running the server

Once the server is set up, run it with:

node server.js

Now, when you visit http://localhost:3000, Express will automatically serve the static files from the public folder.

By following the steps mentioned above, you’ll be well-equipped to start serving static files with Express.js on your own projects.

Link to the official Express documentation:Express js documentation

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top