Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Static Files

User image

Published by

sanya sanya

Published at: 28th Jul, 2023
1.045 mins read

The static files can be served using the express.static middleware. The express.static function is built-in middleware in Express.js and allows you to specify a directory from which to serve static assets.

We can use express.static to serve static files in Express.js as mentioned below -

  • Create a directory in your project where you will store your static files, such as public.
  • Move your static files (e.g., images, CSS files, JavaScript files) into the public directory.
  • In the Express.js application file, require the express module and we can create an instance of the Express application.

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

  • we can the express.static middleware to serve static files from the public directory. For example -

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


When a request is made to your application for a static file, Express.js will look for the file in the specified directory (in this case, public). If the file exists, Express.js will serve it to the client. If the file doesn't exist, Express.js will continue to the next middleware or route.

By serving static files using express.static, we can easily provide CSS stylesheets, images, client-side JavaScript, and other static assets to the clients accessing our Express.js application.

Library

WEB DEVELOPMENT

Basic

Frontend

Backend

Node JS

Node Modules

Restful Routing

Static Files

REST API

Introduction to Node JS

GET vs POST

Database

Interview Questions

FAANG QUESTIONS