DEV Community

Sushil Bishnoi
Sushil Bishnoi

Posted on • Updated on

How to serve html file using nodejs

//The folder structure looks like this 
>public
   >css
      .style.css
.index.html
Enter fullscreen mode Exit fullscreen mode

This code snippet demonstrates how to serve static files using Node.js

const express = require("express")
const app = express()
const path  = require("path")
const port = process.env.PORT || 4000
require('./db/database.js')

const static_path = path.join(__dirname, '../public')

// using middlewares 
app.use(express.static(static_path))
// routes 
app.get("/", (req, res) => {
  res.send("<h1>Hello world</h1>")
});
// server port 
app.listen(port, () => {
  console.log("Server is running")
})
Enter fullscreen mode Exit fullscreen mode

Buy me a coffee: https://www.buymeacoffee.com/sushilk132y

Top comments (0)