How to serve HTML and CSS files using express.js

Writing a whole code in JavaScript file is a mess and not a maintainable. As a good developer, we have to write maintainable code which can be maintained by developers easily in the future. To make this possible in the express framework it serves HTML and CSS files.

Code for serving HTML and CSS files in Express

In the below code, I have created an HTML file in which external CSS is used to change the style of the page. This HTML file is served by express in the port number 3000.

app.use(express.static(path.join(__dirname,’CSS’)); //This command is used to serve the CSS files which are kept in the CSS folder from the working directory.
res.sendFile(path.join(__dirname,’HTML’,’text.html’);// This command is used to send HTML file which is kept in the HTML folder from the working directory and serve to the browser when URL match to the scripts.

FILES : 
main.js

const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname,'css'));
app.use('/html',(req,res,next)=>{
res.sendFile(path.join(__dirname,'HTML','text.html');
});
app.listen(3000);

text.html

This file serves as to the browser when URL match with ‘localhost:3000/html’ which will show a text with background yellow applied by the external CSS.

<html>
<head>
<link href="../css/h1.css>
</head>
<body>
<h1> HTML FILE</h1>
</body>
</html>

external.js

h1{
background-color : yellow;
}

The output is shown below :

Output :

HTML FILE


Check out other blogs as well:
Body parsing in Express JavaScript body-parser
Use of routers in Express JavaScript

Leave a Reply

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