Node Guide

Menu
Menu

Static Files in Express

Adding CSS

In a Node.js/Express application, static files refer to files that are served directly to the client without any processing or modification by the server. These files include things like HTML, CSS, JavaScript, images, and any other assets that are required by the client-side of the application.

Static files are served via the express.static middleware.

Add app.use(express.static("src/public")) to the src/index.ts file to tell Express to serve static files from the "src/public" directory. This means that any files placed in the "src/public" directory will be accessible to clients making requests to your server.

For example, if you have a file named "styles.css" located in the "src/public" directory, you can include it in an HTML file like this:

<link rel="stylesheet" href="/styles.css">

When a client requests the "/styles.css" URL, Express will automatically look for the corresponding file in the "src/public" directory and serve it back to the client.

It's important to note that the path provided to express.static is relative to the directory from where you launch your Node.js process. So, in your case, the "src/public" directory should be located in the same directory as your server file.

By serving static files using express.static, you eliminate the need to handle each static file request manually in your routes. Express will take care of delivering the correct file based on the requested URL. This makes it easier to manage and serve static assets in your application.

In the repo there is a folder set up called src/public. Notice this has a set of subfolders holding CSS and images.

Add the call to the CSS files to the src/views/films.ejs template with:

SNIPPET: src/views/films.ejs

Tip:The above loads two CSS files following the mobile first paradigm.

Displaying Images

Our sample data includes named images for each film, and these are in the static folder at src/public/images. We can have the appropriate image for each film loaded into our template by using the film.filmImage field. Edit the view as follows:

SNIPPET: src/views/films.ejs

The images will now appear in the view. To tidy up the and make maintenance of the views easier next we will look at the concept of partials.

Adding a Page for Displaying Individual Film Data

Create a controller for extracting data for one film:

SNIPPET: src/controllers/controller.ts

Create a route that receives the id as a URL parameter and then passes the id to the getDataById method in the controller.

SNIPPET: src/router/router.ts

The Response object res uses the render() method to call the filmDetails view and pass two values, title and film.. These are then references in the EJS file:

SNIPPET: views/filmDetails.ejs

The hyperlinks in the films view should now link through to the details view.

Next: Modular DRY Code with Partials