Getting Started with Node.js Part 3

Welcome to Part 3 of Getting Started with Node.js. In Part 1, we installed Node.js and ran our "hello world" file through the command console. Node.js becomes really awesome when we can use it as a web server to serve web pages, so in Part 2 we took the same file and set up a Node.js server, and ran the file in the browser.

In Part 3 we will move the content of our "page" to an HTML file so you can get away from putting your HTML in JavaScript strings.

If you haven't done so already, please read Part 1 and Part 2 before continuing. I will assume you have, so you are on your own if you skip them and don't understand something.

First, let's make a new file called server.js. Save it in a convenient place (it's not related to Part 1 or Part 2). I'm going to save mine in a folder called "blogs." The setup will initially be the same as past lessons, so here's a little review. The first line is:

	var http = require("http");

This line creates a variable called http and sets it equal to the HTTP modules that comes with Node.js. If you've been around for a bit, you have probably run into the npm market. It is a place where you can get Node.js written by other people and a crazy, awesome testament to how many great people are working on Node. All of those modules are considered third party because they have to be installed >on top of Node. HTTP (along with many others) is part of Node.js already, so if you've got Node, you've got HTTP. It allows Node.js to handle HTTP traffic, which is what the browser uses pretty much every time you load a web page.

We are going to need another core module to accomplish our task. This one is the fs module, which is short for "file system." Unlike JavaScript in the DOM, Node.js has access to the files on the computer it's being run on. We are going to need it to load up your server.js and we don't need to install it because it's already part of core (Node comes with it, just not enabled). The line is:

	var fs = require("fs");

Nothing new here. It's just getting the fs module into a variable so we can use it. Let's make the server again and listen on port 3000, and add a line to make sure the server loaded up.

	http.createServer(function (request, response) {
	

	//code will go here
	

	}).listen(3000);
	

	console.log("Server is listening for HTTP traffic at port 3000...");

Go ahead and test it out. I call these "sanity checks." It's incredibly important to test your code frequently as you make changes. If you make too many changes before you test again and you get an error, it is exponentially more difficult to find the cause of the error. It may be related to any one change, or worse, a combination of changes, and you'll have to dissect a lot to get there.

Once you've tested and verified it's all working fine, open your terminal window (use cmd-space, type "terminal" and hit enter) and navigate to where you put server.js. If you don't know how to do this, you can drag the folder from finder onto the terminal window. This will drop the path on the command line. You just need to hit enter, then:

	node server.js

The screen should look something like this:

In Part 2, we wrote the status code, set content-type to plain text, and sent the response back to the browser. This time we are going to use the fs module to get an HTML file. Inside of createServer, write this:

	response.writeHead(200,{'content-type':'text/html'});

	var theHomePageHTML = fs.readFileSync('homePage.html');

	response.write(theHomePageHTML);
	response.end

Just as before, we are writing the status code (200 means, "OK" or "success"), but we are changing the content-type to HTML and then using the readFileSync method from the fs module to get the contents of a file, in this case, homePage.html. This means that when any browser comes to this site (http://localhost:3000), Node will be listening. It will go and get the contents of that HTML file, send them back to the browser, and close the connection. Sanity check. Go back to the terminal and close your Node program (control-c), run the file again (node sever.js), then go to http://localhost:3000. You should see something very close to this:

 

The first few lines are not helpful, but the line that starts wtih Error: ENOENT, is.

	Error: ENOENT: no such file or directory, open 'homePage.html'

We asked the fs module to get the contents of homePage.html, but it doesn't exist! What's the fix? Let's make it. You can use whatever you want here, but I'm going to keep it simple.

<h1>Ha ha! I escaped the clutches of node!</h1>

<p>I'm back to my good old HTML days in week 1</p>

<p><a href="http://www.digitalcrafts.com">Click here</a> to check out a cool site.</p>

You'll need to start the server up again. Just type "node server.js" and you'll get the friendly message "Server is listening for HTTP traffic at port 3000..." Now go refresh the page at: http://localhost:3000. Voila. The FS module doesn't complain this time because the file exists and your content loads up. Now you can manage the html the way you are used to, but on your very own Node.js server!

That's all for today! Check back for Part 4 where we will add a CSS and JS file.

Interested in learning more about Node.js? It's just one of the many programming languages and frameworks we cover in our Full Stack Immersive program. Click the button below to download a course packet to find out more about our programs and curriculum!

Download Course Packet

 

 

 

Author
Rob Bunch

Immersive Web Instructor, Atlanta