Nodejs has a deceptively short source code for the standard “hello, world”
version of an http server.
// File: hello.sj
"use strict";
const http = require("http");
const server = http.createServer();
server.on("request", handleRequest);
server.listen(8080, handleListen);
function handleRequest(request, response) {
console.log("Request url: %s", request.url);
response.writeHead(200, {"Content-Type" : "text/plain"});
response.end("Hello, World!");
}
function handleListen( ){
console.log("Server is listening on port 8080");
}
We can run this server with the following command:
$ node hello.js
Server is listening on port 8080
In which case the program in the console will simply stop without terminating. This is because we told our process to listen on port 8080 for any http requests, and have not given the process any specific commands to terminate. Since our web browser can send http requests, we can open up our browser and attempt to communicate with our Nodejs web server. If we type
And in our Nodejs console we should see the output of
Request url: /
Request url: /favicon.ico
Which is somewhat curious but easily explainable. For the “/”, we simply sent a request to http://192.168.1.16:8080
from the browser, without appending anything onto the end. The browser automatically adds the slash at the end, representing the root directory. The “/favicon.ico” is another browser quirk. Most web sites will have an icon which is displayed on the tab of that page. This icon is referred to as a “favicon”, and the browser will automatically send a request to the web server to see if it exits. In this case it doesn’t and nothing is displayed.
That alone is simple enough, but things become more confusing when we try adding more text on to the end of our url.
We can try http://192.168.1.16:8080/aaaaaaaa
or any other text onto the end of the url we request and there will be no change. For any and all requests our server will simply respond with “Hello, World!”. While this may seem a little baffling at first, because with other web servers, if you put in a random set of letters or characters into the request, you would expect to get a 404 or some other error to the effect.
function handleRequest(request, response) {
console.log("Request url: %s", request.url);
response.writeHead(200, {"Content-Type" : "text/plain"});
response.end("Hello, World!");
}
If we take another look at out handleRequest
function the response quickly
becomes apparent. For all requests, regardless of the context, our server is
simply programmed to return the text “Hello, World!” for all requests. So how can we program our Nodejs server to do something more functional? We will continue in the next chapter we will be expand our basic text server into a basic file server.