Step 6
Update the server.js
file as follows:
const http = require("http");
const server = http.createServer((request, response) => {
response.writeHead(200, { "Content-Type": "text/html" });
response.write(`<h1>Hello HTTP Module!</h1>`);
response.end();
});
server.listen(7000);
console.log("Listening! (port 7000)");
Save the file and run it:
node server.js
Open the browser and visit http://localhost:7000/. You should see the following:
When you run this script, the process sits there and waits. When a process is listening for events (in this case, network connections) node will not automatically exit when it reaches the end of the script. To close it, press Control
and C
.
The call to server.listen
causes the "server" (your computer in this case) to start waiting for requests on port $7000$. This is why you have to connect to localhost:7000
to "speak" to this server, rather than just localhost, which would use the default port $80$.
The function argument to createServer
is called every time a client visits http://localhost:7000/
. The request
and response
bindings are objects representing the incoming and outgoing data.
The writeHead
will write out the response headers. The number 200
is the status code, and the second argument contains header values. It sets the Content-Type header to inform the client that we'll be sending back an HTML document. The write
method is the actual response body (the document itself). Finally, response.end()
signals the end of the response.