We'll be creating a server that returns the present time and date to the user, this server would be run on our localhost on port 3000.
We start by making our directory and creating the file that will house the code
We load the http module that’s standard with all Node.js installations. Add the following line to hello.js
The http module, contains the function to create the server.
We define 2 constant that our server would be bound to, the host and the port respectively. The value localhost is a special private address that computers use to refer to themselves, and it's available to the local computer, not just any local network, or to the internet. The port is a number that servers use as an endpoint or “door” to our IP address. When we bind our server to this host and port, we will be able to reach our server by visiting http://localhost:3000 in a local browser.
We create the function that would return the present time and date when we start the server.
Now we can create our server, and make use of our request listener function.
- All request listener functions in Node.js accept two arguments: req and res (we can name them differently if we want).
- The HTTP request the user sends is captured in a Request object, which corresponds to the first argument, req.
- The HTTP response that we return to the user is formed by interacting with the Response object in second argument, res.
-
In the first line, we create a new server object via the http module’s createServer() function. This server accepts HTTP requests and passes them on to our request Listener function.
-
The last line of the function, res.end(clock);, writes the HTTP response back to the client who requested it. This function returns any data the server has to return. In this case, it’s returning Date and Time function, which is called by "clock".
- After we create our server, we must bind it to a network address, We do that with the server.listen() method. It accepts three arguments: port, host, and a callback function that fires when the server begins to listen. Although all of these arguments are optional, it is usually a good idea to explicitly state which port and host we want a web server to use.
Now we have our server, let's see it in action and test it by running our server. In the console we should see this output
When we click on the link it opens up our web browser to this page
After confirming the server runs the D&T function, we can stop the server process with ctrl + c