Learning while teaching — Class 2

Luca Gobbi
8 min readNov 1, 2015

--

Intro

Hello again, this is our second class and today I’m going to introduce 3 new stuff:

  • HTTP: Basics of what it is.
  • NPM: The node package manager
  • Express.js: First steps to setup an basic application

At this point you should be asking yourself: Where I’m going to use the last class in here? And the answer is: everywhere! I’ll try to point some places but basically you’ll notice that Classes are everywhere and knowing a little bit about them will help you understand how to use libraries and packages.

And…where I can find the code?

The complete code will be available on my GitHub under https://github.com/lucavgobbi/lwt-class2

Need help?

Take a look here under “How we can talk” to see how you can contact me.

HT What? (HTTP)

HTTP stands for HyperText Transfer Protocol and is one of the protocols available on the Application Layer of OSI Model but this is subject for another post. What we should care about here is what HTTP is used for and how it will be important to us.

Putting it on simple terms: HTTP provides a way to access documents on the internet through requests, for instance: if you type http://www.facebook.com in your web browser’s address bar it will request a document (the Facebook home page) for one of Facebook servers. Of course, there is a lot of stuff involved but for starters lets say that you GET this document from Facebook. And when you type your username and password on Facebooks’ page and hit enter you are POSing the text you typed (and lots of other information) to Facebook’s server which will respond with other document with your results. GET and POST are two of several methods available in HTTP for us to deal with online documents.

The address (http://www.facebook.com) is your URL, URLs can also contain parameters like in https://www.facebook.com/lucavgobbi?fref=nf “?fref=nf” tells Facebook’s server that the value of “fref” is “nf” whatever this means to their server. In this case, “fref” tells the new document from where you reached that document, “nf” is news feed, so you can try it yourself, open any link from your newsfeed on Facebook and this parameter might be present. This behavior is implemented on Facebook’s server which means that for other URLs, “fref” might mean something different or probably nothing.

So in a very general way, HTTP is a protocol for requesting documents which has several methods such as GET, POST, DELETE, PUT where each method has an specific function. The documents can be accessed through an URL or Address and you can specify parameters to the server.

Does it look weird right now? Don’t worry, we are going to see how this works in real life and I promise you it will make sense ;).

NPM, The Node Package Manager

If you have already installed node.js correctly NPM is already installed in your computer. (If not, check this post).

Let’s start checking if you have it installed on your computer. First open your terminal.app or cmd and type:

npm -v

If some numbers appear on the terminal you are good to go.

But this topic is not about using NPM. It’s about what it is.

NPM is a package manager written in node.js which contains hundreds of thousands of javascript packages. With a simple command you can install, update or remove a package from your computer or project without having to concern about dependencies.

Dependency? WHAT?

A dependency is any package that your project or other project might need to run. For example: if your project (P1) needs a math package (M1) with functions to calculate exponent power and this package requires another package (P2) that has functions to multiply then your project (P1) is dependent on M1 and M1 is dependent on M2. In order to run your project you will need to install M1 and M2 on every server or computer that you want to run it. Now think about a huge project with lots of packages, solving these dependencies doesn’t look nice right? NPM is responsible to solve all dependencies that a package might have, for example, later in this class we will install Express.js using NPM and it has lots of dependencies but NPM will take care of this!

Express.js

Intro

Express.js is a Web Framework for node.js; It helps programmers to build web applications faster and better with less code by offering several classes, utility methods and tools for you. In this part of class, we will learn how to start our project and write a pretty basic Express.js application.

Initializing NPM

Do you remember NPM? Great! We are going to use it right now.

First think that you need to do is create the directory where your project will be saved. I recommend you doing it using the terminal.app. Now that you are becoming a programmer you need to get used to it. So, to create your directory just move to where you want to create it in your directories and type (Change “NewDirectoryName” for whatever you want):

mkdir “NewDirectoryName”

After that, let’s move inside it:

cd “NewDirectoryName”

In order to init the NPM and create the package.json we will run this command inside the project directory

npm init

This will output something like this:

NPM Init

Basically NPM is asking you some questions to create your package.json file. In this initial moment you can accept all the defaults by pressing enter.

After you finish it you show you the final package.json

NPM Package.json confirmation

Don’t worry, yours will not be the same as mine and you don’t need to worry about it.

Now, if you check your project folder you might be able to see a file called package.json. This is the file where NPM stores some configuration and the dependencies of our project. I’ll explain later how this file is important and how does it helps us a lot while developing.

Becoming a dependent of Express.js

So, how to add some dependencies to package.json? Well there are two main ways to do it. The first one, we will use the command is the project directory:

npm install package-name --save

The first 2 words looks obvious right? The third is the package name, in our case: express. The last part of the command: “ — save” tells npm to save this package to our package.json file.

After running the command, you will see an output like this:

Express dependencies

All these weird names are other packages that Express requires to run, they are Express dependencies. Now think for a second, what if you have to install all these by hand? Or worse, what if, the new version of Express requires a different version of one of these packages? Can you imagine how chaotic it would be to update manually all these packages? And remember, we are just installing our first package.

You also may take a look back on your package.json file. In the end of it a new text was appended:

"dependencies": {
"express": "^4.13.3"
}

This is just telling the NPM that your project requires this version of Express to run.

The second way to install or add a package to your project is editing the package.json file. You could have added the lines above and executed the command instead.

npm install

The result would be the same. But honestly I prefer the first way than the second.

Coding your first app

Finally, now is time :) you will code your first “real” app and see the results of it.

If you’ve done the process above correctly you should have a folder structure like this without LICENSE and .gitignore in the root folder:

Folder structure

Ok, now let’s create our first file in the project. Open your favorite editor (if you haven’t one check some suggestions here) and create a file called index.js (later in another class I’ll explain why this name).

And write this code in the file:

Ok, so step by step:

var express = require('express');

This includes (or require) Express framework to be used in our code. require(‘package-name’) is one function provided by node.js that help us load libraries and packages, later we will see how it works, but for now let’s just assume that it finds express and assign it to a variable.

var app = express();

Now we get the variable app to be an instance of .express(). This variable will be used a lot and is how express.js provide us his methods. Note that you could use any name you wanted instead app.

app.get('/', function (req, res) {
res.status(200).send('Hello World!');
});

See? We are already using the app variable! Now we are mapping the first route of our application ‘/’, the .get(…) method on app maps the URL specified as first parameter to GET method on HTTP to a callback (more about callbacks next class). So now, if someone request a document in your server using a GET HTTP method he will get an answer.

The callback in this case is a function which receive two parameters, req and res, req is the request data and res is the response data. Remember in the begging of this class that I told you that the browser sends a lot of data to the server? Well, you can access it on req variable!

So, what we do inside our callback is invoking two methods of res variable. The first one .status(200) add the HTTP STATUS 200 to our response, in HTTP this means that everything went OK. And the second method .send(‘Hello World!’) sends Hello World! as a response to who requested it.

var server = app.listen(3000, function () {
console.log('Hey I am running ;)');
});

And last but not least, we need to define what port our server will use and start listening it. The .listen(…) method provided by app variable. The first parameter is the port where the server will listen, the second is the callback function when the server is listening.

Note: Usually when you access a webpage the server is running on port 80 or 443, these are the defaults ports for HTTP.

Running your first app

Now open your terminal.app, go to the root folder of your project and type

node index.js
Run server output

Open your browser and type: http://localhost:3000 and here it goes ;)

Browser

Extra

So, let’s check if you have learned. Try to add a new route (URL) to the server, the route will be http://localhost:3000/test and it should answer “This is another route”

The answer is posted on the GitHub Project but I highly recommend you trying to do it alone before, If you have doubts send me an email me@lucavgobbi.com or tweet @lucavgobbi.

Hope you enjoyed. See you next class ;)

*Special thanks to Luiz Fernando Suzuki for English corrections.

--

--