Build Your Website — Like A Programmer (Part 2)

Eric Adamski
6 min readJun 2, 2016

--

If you managed to get here without completing Part 1 it may be OK, you just need to ask yourself a few questions:

  • Do I have a github repository setup?
  • Do I have a text editor setup?
  • Do I have Nodejs and NPM install?

If you answer no to any of these questions, pop over to Part 1 it will walk you through some setup which will make your life easier down the road. Part 3 is here.

Now then, you have got your environment setup lets actually do some creatin’! We will need to create a package.json file to keep track of our project dependencies. In atom create a package.json file by right clicking on the left most side of the window and selecting new file. If you want to be a little more computer sciencey you can create empty files in the terminal by doing

> touch package.json

A shortcut to creating this file is typing ‘npm init’ into your terminal and following the instructions. You will still need the dependencies that are listed here.

Inside your package.json file we will add some important information about our application, it will look like this:

{
"name": "your-own-website",
"version": "0.0.1",
"description": "My own personal webpage."
}

This file has to be in JSON format, also FYI JSON is how objects are represented in Javascript so you can get used to see things written in this way. The important part of this file is the dependencies section, take a look at the complete package.json below.

You will also want to add this file .gitignore:

Save that file, head over to your terminal window and then type:

> npm install

This will install all the packages under the dependencies section, they are some packages we will use in our development. Once that is done we must create our entry point for the server, create a file called app.js. This is where we begin our journey through Javascript!

We will begin by creating our server using Express. First we will need to include all the packages we will be working with, like so

'use strict';let express       = require('express');      
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let compression = require('compression');

Each require statement will allow you to use the code stored in each of those packages. Now create your application (Server),

let app = express();

This is called a constructor, it creates a new object of the type given, in this case it’s the express object we included earlier. We must set up the middleware for our server to use. We will use the app variable that we just created,

app.use(compression());
app.use(favicon(path.join(__dirname, 'public', 'img', 'favicon.png'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

Each piece of middleware helps the server function in a way that makes our lives a little easier. Finally we will attach our static files to be served and the routes we would like to use. The resulting file will look something like this,

You can think of the file above as a configuration file telling your server what it has to utilize in order to process requests. Next we will create our launch script, it will be what we call in order to run our server and serve up our website. Take the file below and put it in a file called www inside of a directory (folder) called bin.

As of right now our directory (folder) structure will look like this,

<your-username>.github.io/

├── .gitignore
├── package.json
├── app.js
└── bin/
└── www

We need to add a few more files to get our server ready for hosting! So add the following files:

  • router/index.js
  • views/index.html
  • assets/scss/_default.scss
  • public/img/favicon.png (pick your own png image)

Once those have been added your directory structure will look like

<your-username>.github.io/

├── .gitignore
├── package.json
├── app.js
├── views/
│ └── index.html
├── public/
│ └── img/
│ └── favicon.png
├── assets/
│ └── scss/
│ └── _default.scss
├── router/
│ └── index.js
└── bin/
└── www

We won’t be touching the html and scss files until the next part of the tutorial, though it will be easier to understand the serving process with the files in the tree.

Lets open up the router/index.js file, this will be where we define the pages of our website. First let’s import the required packages,

'use strict';let express = require('express');
let router = express.Router();
let path = require('path');

The router is the most important part of this file, it is what will be handling the requests made by people trying to access your site. Let us create the landing page. We would expect that the landing page is the very first part of your site you want someone to see. So if someone goes to your website address, http://<your-username>.github.io/, we want them to see our landing page. The route for that will be defined as follows,

router.get('/', (request, response, next) => {
response.status(200).sendFile(path.join(__dirname, '..', 'views', 'index.html'));
});

Let’s dissect that piece of code.

router.get

Is handling every time someone sends a GET request to our server. A GET request is asking our server to send some information, in our case it will be our landing page index.html.

There are some standard HTTP request types you can see them defined here, in this tutorial we will only be using GET requests.

The next part of the router handler is the path. For a home page the usual path, which is known as the root, is ‘/’. If we had an ‘about’ page the path would look something like ‘/about’. It is exactly like navigating on your computer to try and find a file, we are just accessing that file from someone else's computer. So when someone asks we send them some information (GET request) we must deliver some content, in our case it is a file hence the ‘sendFile’ function call. Once we have made that call we let the users browser handle the rest!

Below is the index.js file in its entirety. The first ‘router.get’ looks at all requests to every page (route) and looks to see if it has been requested from some other domain (the url), if so it rejects to serve it as a security measure.

Now we have a functioning server! Head over to your terminal to test it out

> npm run dev

Then pop over to your browser and go to

http://localhost:3000/

How exciting, you see nothing! Add the code below into your index.html file and the refresh your browser.

<h1> Hello World! </h1>

The code above is HTML, we will be covering that and SCSS/CSS in the next tutorial, but it is no fun to see nothing from your server. After you refresh you should see something like

Now we need to store all this information into github, so head over to that trusty terminal and type

> git add . // adds all the new files to be tracked> git commit -am "Added: the server" // a unique message to describe the changes you made> git push --set-upstream origin feature/nodejs-server

We have completed the server so we will close the branch feature/nodejs-server and next time we will create a new one to work from.

With git flow

> git flow feature finish nodjs-server

Without git flow

> git checkout develop> git merge feature/nodejs-server> git push> git branch -d feature/nodejs-server // delete locally> git push origin --delete feature/nodejs-server // delete remote

It is a good idea to do commits more often so that if you mess up you don’t have to rewrite a lot!

Next part of this tutorial we will work to get our website looking super purty! Have I included enough, too much, information? Leave me some feedback!

--

--

Eric Adamski

I want to help people discover their purpose. Entrepreneur. Software Developer. Father. Guy who just generally likes to learn!