This is a sample basic Node.js website using plain HTML files and the built in http and fs modules.
This tutorial will walk you through the creation of a very basic website using only Node.js built in modules. Follow these steps to create a Node.js website:
-
Create a folder for your Node.js project.
-
Create a home page HTML and call it
index.html
. Add the required HTML tags and some basic content in theindex.html
file. -
Create a second file and for now, call it
another-page.html
. Add the required HTML tags and some basic content in theanother-page.html
file. -
Add a link in the
index.html
page toanother-page.html
. And add a link in theanother-page.html
toindex.html
. This will allow for easy testing of pages. -
Create a new file called
app.js
. -
In
app.js
import the required modules:var http = require('http'); var url = require('url'); var fs = require('fs');
-
Create an http server:
http.createServer(function (req, res) { }).listen(8080);
This will start a web server. The server is available to test by opening a browser and using the URL
http://localhost:8080/index.html
. -
Inside the
createServer
function add code to fetch the current URL:var q = url.parse(req.url, true); var filename = "." + q.pathname;
-
Inside the
createServer
function, after the the previous lines of code, add code to load the appropriate HTML file based on the URL. For example the URLhttp://localhost:8080/index.html
will load theindex.html
file.fs.readFile(filename, function(err, data) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); });
-
Inside the
readFile
function, add code that will display an error message in case the requested URL does not match an exsting file:if (err) { res.writeHead(404, {'Content-Type': 'text/html'}); return res.end("404 Not Found"); }
-
To test your Node.js website, open up a terminal, use
cd
to navigate to your project folder, and usenode app.js
to start your file. Then open a browser and visit the URLhttp://localhost:8080/index.html
.
Your final code in app.js
should look like this:
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Full tutorial URL:
https://codeadam.ca/learning/nodejs-website.html