Express

Node.js Express Static Files

Serving Static Files

Node.js Express static files serve assets with express.static.

Introduction to Serving Static Files

In web development, static files such as images, CSS files, and JavaScript files are essential components of most web applications. Serving these files efficiently is crucial for application performance and user experience. In Node.js Express, you can serve static files using the built-in express.static middleware, which is both efficient and easy to use.

Setting Up Express Application

Before you can serve static files, you need to set up a basic Express application. This involves installing Express and creating a simple server. Here's how you can do it:

Using express.static Middleware

To use express.static, pass the directory path to the middleware function. It is common to serve static files from a directory named public. Here's how to do it:

Creating a Public Directory

Create a directory named public at the root level of your project. Place all your static files like HTML, CSS, images, and JavaScript files in this directory. For example:

  • public/index.html
  • public/style.css
  • public/script.js

Accessing Static Files

Once you've set up express.static, you can access your static files directly via the browser. For example, if your server is running on http://localhost:3000, you can access:

  • http://localhost:3000/index.html for your HTML file
  • http://localhost:3000/style.css for your CSS file
  • http://localhost:3000/script.js for your JavaScript file