Welcome to part 6 of the NodeJs tutorial. Today I want to discuss adding views to our node js app and configuring a public folder to add external CSS files.

In routes Folder


const express = require("express");
const router = express.Router();

const path = require("path");

router.get("/", (req, res, next) => {

  res.sendFile(path.join(__dirname, "../", "views", "shop.html"));  //shop.html in views folder
 
});

module.exports = router;


Explanation

we add routing and then set the file we want to display

const path = require("path"); //import path core module

router.get("/", (req, res, next) => {

  res.sendFile("./views/shop.html");
  slash refers to root folder globally so this would not work

  res.sendFile("D:/Node/FirstScript/views/shop.html");
  this will work but too robust

  so we use-> path core module                           

res.sendFile(path.join(__dirname, "../", "views", "shop.html"));
 
directly where the HTML file is located
join - returns the path concatenating each one
__dirname - global var; hold absolute path on our os to this project folder
                                          ex->D:\Node\FirstScript\routes\
});

module.exports = router;




More cleaner way to add a path

add a helper folder
->path.js
            const path = require('path');

            module.exports  = path.dirname(process.mainModule.filename)
//process.mainModule.filename -> refers to app.js
//take the directry name of it and pass

then import as ->const path = require("../helper/path");  //where the path file is located
but const path = require("path"); <- this will also needed (drawback)


IMP

Html files can be access as above but css or image files we need to setup a public folder

we cannot directly add css files into html pages
<link rel="stylesheet" href="/css/main.css">

So set a public folder -  > public/css/main.css

Now configure the App.js
     we have to add a new middleware -> express.static

in app.js ->
            app.use(express.static(path.join(__dirname, "public")));     //Can add any folder

grant read access public folder //only grant read access
now external files (such as css) can be accessed

Now the css file can be imported as
<link rel="stylesheet" href="/css/main.css" />
[No need of ‘/public/css/main.css because we set the public folder]