Welcome to a quick tutorial on how to create an HTTP web server with NodeJS. Yes, you read that right. It is possible to run a simple web server with NodeJS if you are lazy to install a full-featured server stack.
One of the easiest ways to set up a NodeJS HTTP web server without writing a single line of code is to:
- Install the HTTP Server module globally –
npm install --global http-server
- Run the server
http-server PATH/HTTP/
- The server can now access via
http://localhost:8080
That covers the quick basics. But read on if you are interested to create your own server using the HTTP module!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
- Install the MIME module
npm install mime-types
. - Change the
const host
settings in2-better-server.js
. - Run
node 2-better-server.js
.
EXAMPLE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
NODEJS HTTP SERVER
All right, let us now get into the examples of creating a simple NodeJS web server.
BASIC HTTP SERVER
// (A) CREATE SERVER
const server = require("http").createServer((req, res) => {
// (B) RESPOND TO CLIENT (SERVE DUMMY HTML PAGE)
res.writeHead(200, { "Content-Type": "text/html" });
res.write("<html><body>It WORKS!</body></html>");
res.end();
});
// (C) LISTEN TO PORT 80
server.listen(80);
console.log("Server is running!");
A raw basic HTTP server is as simple as:
- Create an HTTP server
server = require("http").createServer()
- Set it to listen to port 80 (or whatever open port you want) –
server.listen(80)
Of course, we also need to handle and respond to user requests.
req
is the user request (for which page, from which domain, etc…)res
is the response we give to the user. In this example, we reply with an HTTP 200 (OK) and serve dummy HTML.
Of course, this example is not productive, so let’s upgrade it in the next example.
A SLIGHTLY BETTER SERVER
// (A) "VIRTUAL HOSTS" & MODULES
// MIME TYPES MODULE REQUIRED - "npm install mime-types"
const hosts = {
"default" : "D:/http",
"site-a.com" : "D:/sitea",
"site-b.com" : "D:/siteb"
},
http = require("http"),
fs = require("fs"),
mime = require("mime-types");
// (B) CREATE SERVER
const server = http.createServer((req, res) => {
// (B1) PATH TO LOAD FILES FROM
let path = hosts[req.headers.host]
? hosts[req.headers.host]
: hosts["default"];
// (B2) THIS SIMPLE SERVER WILL ONLY SERVE FILES
let rfile = path;
rfile += (req.url == "/") ? "/index.html" : req.url ;
if (fs.existsSync(rfile)) {
if (fs.lstatSync(rfile).isDirectory()) { rfile = null; }
} else { rfile = null; }
// (B3) NOT FOUND OR IS FOLDER
if (rfile === null) {
res.writeHead(404, { "Content-Type": "text/html" });
res.write("<html><body>Not Found</body></html>");
}
// (B4) LOAD & SERVE FILE
else {
res.writeHead(200, { "Content-Type": mime.lookup(rfile) });
res.write(fs.readFileSync(rfile));
}
// (B5) CLOSE
res.end();
});
// (C) LISTEN TO PORT 80
server.listen(80);
console.log("Server is running!");
- Load the required modules, define the “virtual hosts” and their respective folders. Remember to install the
mime-types
module or this will not work. - Create the HTTP server as usual, but we expand on how it handles the user requests.
- Basically, load the user’s requested file.
- Serve a 404 error if the file is not found.
- Listen to port 80.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
NOT FOR PROFESSIONAL USE
Yes, it is interesting and fun to create your own Javascript HTTP server. But this simple example is not to be used in “the real world”… If it is not obvious enough, it is lacking in features and security. Use this for quick testing and studying only, it is far from “a real webserver”.
LINKS & REFERENCES
- HTTP Module – NodeJS
- Other popular Node HTTP server modules – http-server and Express
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!