The missing steps after Hello World
Introduction
If you have been coding in HTML and are recently exploring Node.js tutorials (for beginners), you might have encountered a small problem, like I did. OK, so I have Hello World now, what next?
I’m assuming that you are using Express in this article. (You can refer to my earlier articles on Node.js.)
Creating the html and css files
Create a test.html file in root of your project:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/mystyle.css">
</head>
<body>This is our HTML file.</body>
</html>
Also create a mystyle.css file:
body{
color: red;
}
Loading the html file
Import path
import path from 'path';
import {fileURLToPath} from 'url';
This helps the project load your .html file.
Add a new .get listener to your application.
app.get("/showfile", (req, res, next) => {
// show the page
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const _retfile = path.join(__dirname, 'test.html');
res.sendFile(_retfile);
});
The app.ts/app.js file should look something like this:
import express from 'express';
import path from 'path';
import {fileURLToPath} from 'url';
var app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});
app.get("/", (req, res) => {
res.send('Hello World!')
});
app.get("/showfile", (req, res, next) => {
// show the page
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const _retfile = path.join(__dirname, 'test.html');
res.sendFile(_retfile);
});
Open the page on your browser at:
http://localhost:3000/showfile
You will notice that the .html file loads but the CSS is not applied. This is because our new web page cannot find the CSS in the current path.
Adding /public
The solution turned out to be relatively simple. First, create a /public folder in the root of your project. This is like the /var/www/html and serves as the root of the website. We create the /js and /css folders here.
Move our mystyle.css file to the /css folder here.
Adding app.use
In the app.js file, ensure that you have this line added:
app.use(express.static('public'));
The app.js file should now look something like this:
import express from 'express';
import path from 'path';
import {fileURLToPath} from 'url';
var app = express();
app.use(express.static('public')); // this is added!
app.listen(3000, () => {
console.log("Server running on port 3000");
});
app.get("/", (req, res) => {
res.send('Hello World!')
});
app.get("/showfile", (req, res, next) => {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const _retfile = path.join(__dirname, 'test.html');
res.sendFile(_retfile);
});
You should now see your .html file displayed with the CSS applied correctly.
External JS files for DOM manipulation can be added to the /public/js folder in the same way.