,

Chapter 2: Serving Static Files with Node.js and Express.js

Posted by

Node.js & Express.js Series | Chapter 2 | Serving Static Files

Node.js & Express.js Series | Chapter 2 | Serving Static Files

In this chapter, we will discuss how to serve static files using Node.js and Express.js.

Static files can include HTML, CSS, JavaScript, images, and other resources that do not change dynamically. In a web application, these files are served directly to the client without any processing by the server.

Node.js is a server-side JavaScript runtime, and Express.js is a web application framework for Node.js that provides a set of features for building web applications. Together, they make it easy to serve static files in a web application.

To serve static files in Node.js and Express.js, we can use the express.static middleware provided by Express. This middleware function takes a root directory as an argument and serves files from that directory. Here is an example:

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

app.use(express.static('public'));

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

In this example, the express.static('public') middleware will serve files from the public directory. If a request is made for a file that exists in the public directory, Express will serve that file to the client.

We can also specify a path prefix for the static files by providing a URL path as the first argument to express.static. For example:

      
app.use('/assets', express.static('public'));
      
    

This would serve files from the public directory at the /assets URL path. So a request for /assets/css/styles.css would serve the styles.css file from the public/css directory.

With express.static, serving static files in Node.js and Express.js is simple and efficient, allowing us to easily include CSS, JavaScript, and other resources in our web applications.