Let’s dive straight in!

So, now that we’ve covered the basics of Node, let’s jump into practical use: setting up a makeshift server to run our html code.

The process of doing this is very simple. All you need is a bit of Javascript knowledge, 2 node js modules and some creativity!

Since Node js is simply an environment built off of Javascript, we’ll start off with a new javascript file. For this example we’ll name it app.js”.

Untitled

To set up an http server, we’ll need to import the http module from Node. This will help us spin up our local host server.

To include a library in Node js, we simply use the require keyword containing the library name in a string. In this case, to import the http library we would use:

(There are https libraries for node js, but we’ll discuss that is outside the scope of this course).

(There are https libraries for node js, but we’ll discuss that is outside the scope of this course).

Now we have to define a port that node will be listening to. The port number must be in the range 2-65535 as 0, 1, and anything past 65535 is not recognized by Node as ports. You can choose to define the port as a variable prematurely for easy switching or define it later on when it is necessary. For example, defining the port 80 looks like:

Untitled

Now, in order to render a file we are going to need to use the fs, or the File System module, in order to parse the file and write it to the node http server. The import process for the File System module is identical to that of the http module:

Untitled

Now that we have all our modules, let's get started with the actual code.

First, we create a server using the http module with the command http.createServer. In the example, we stored this server inside a new object called server.

This will look something like this:

Untitled