Creating a server in Node.js

Node.js is the server side for JavaScript. It is a tool that helps us host websites and make request between client and server. I will be demonstrating how to create a very basic server in Node.js. First off, you want to start off with these in your code:

var http = require("http");
var fs = require("fs");

The first line of code is the grab the built-in http in the node.js. It is necessary when using node.js. The second line is used to load the pages that we want to display. It is not required in the most basic server, but will need it if we are planning to have multiple pages on a website. Next, we want to do:

var server = http.createServer(requestHandler);

This is the method where we actually create our server. The createServer() method is what creates our server using the required http. The requestHandler function is how we are going to handle users’ requests. We need to defined it so where is typically how we do it:

function requestHandler(request, response) {
if(request.method === "GET" && request.url === "/") {
  response.writeHead(200, {"Context-Type": "text/html"});
  fs.createReadStream("./index.html").pipe(response);
} else {
  send404Response(response);
 }
}

In plain English, it would translate as: If the user’s request is a GET request (user is requesting the home page), then display the content of that page. If the page does not exist, then send an error message. We will notice that there is a function that is called send404Response. The function returns an error response. Here is how we will define it:

function send404Response(response) {
  response.writeHead(404, {"Context-Type": "text/plain"});
  response.write("Error 404: Page not found!");
  response.end();
}

We would want write out our response and end it. Lastly, we want the server to be listening on a port. Usually, it is port 8080 or 3000. Here is how we would do it:

server.listen("8080");

This what it looks like if we put it all together:

var http = require("http");
var fs = require("fs");
function send404Response(response) {
response.writeHead(404, {"Context-Type": "text/plain"});
response.write("Error 404: Page not found!");
response.end();
}
function requestHandler(request, response) {
if(request.method === "GET" && request.url === "/") {
response.writeHead(200, {"Context-Type": "text/html"});
fs.createReadStream("./index.html").pipe(response);
} else {
send404Response(response);
}
}
var server = http.createServer(requestHandler);
server.listen("8080");

This is the basic way of creating a web server.