3 Ways To Create HTTP Server With NodeJS (Simple Examples)

Welcome to a tutorial on how to create an HTTP web server with NodeJS. So your project needs to deal with a web server? Well, there are 3 common NodeJS modules that we can use – Read on for the examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

NODEJS HTTP SERVER

All right, let us now get into the possible ways of creating a simple NodeJS web server.

 

1) USING THE HTTP MODULE

1a-http.js
// (A) LOAD REQUIRED MODULES
// npm i mime-types
const http = require("http"),
      path = require("path"),
      fs = require("fs"),
      mime = require("mime-types");
 
// (B) HTTP SERVER
const server = http.createServer((req, res) => {
  // (B1) SERVE HTML HOME PAGE
  if (req.url == "/") {
    let file = path.join(__dirname, "/1b-index.html");
    res.writeHead(200, { "Content-Type": mime.lookup(file) });
    res.write(fs.readFileSync(file));
  }
 
  // (B2) NOT FOUND
  else {
    res.writeHead(404, { "Content-Type": "text/html" });
    res.write("<html><body>Not Found</body></html>");
  }
  res.end();
});
 
// (C) LISTEN TO PORT 80
server.listen(80);
console.log("Server is running!");

NodeJS comes with a default http module, and it is entirely possible to “manually build” a custom web server with it.

  1. Load the required modules.
  2. When a user accesses the website, this will load the HTML file – Use req.url to get the URL.
  3. Start the server, and listen on port 80.

Yep, it can get kind of complicated. But at least you have a lot of control over building your own web server.

 

 

2) EXPRESS SERVER

2a-express.js
// (A) LOAD REQUIRED MODULES
// npm i express
const express = require("express"),
path = require("path");
 
// (B) INIT EXPRESS SERVER
const app = express();
 
// (C) SERVE STATIC FILES + HOME PAGE
app.use("/public", express.static(path.join(__dirname, "public")))
app.get("/", (req, res) => res.sendFile(path.join(__dirname, "/2b-index.html")));
 
// (D) START SERVER
app.listen(80, () => console.log(`Server running at port 80`));

Next, we have a node module called “Express”. This is my preferred option, and it should not be difficult to see why:

  • (A & B) Load and initialize the required modules.
  • (C) Specify the “endpoints” and “files”. Don’t have to manually deal with all those crazy MIME and HTTP response code stuff.
  • (D) Start the server.

 

 

3) HTTP-SERVER

Finally, there’s another “zero configuration” HTTP server.

  • Install the HTTP server globally – npm i http-server -g
  • Run – http-server
  • See their documentation for more options.

Not a huge fan of this one.

 

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

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!

Leave a Comment

Your email address will not be published. Required fields are marked *