I bet you’d love NodeJS — Part 1

Wojciech Bilicki
7 min readFeb 5, 2018

This series of articles are written as notes and help for participants of the workshop that will be held in OKE Software in Gdańsk Poland. It is by no means a comprehensive guide to the NodeJS technology itself.

Pug and Express

This part assumes you have the NodeJS and NPM installed. If not go to https://nodejs.org and grab yourself an installer. Also, I will be using Yarn for dependency management, so if you’d like to follow along install it, too.

In the first article regarding NodeJS, I’d like to start with explaining what NodeJS is, why it is important and how to use it to build your first, simple site.

We will try to dig deep into the NodeJS in the next parts. For the time being, all you need to know is that NodeJS is a JavaScript runtime. But what does it mean? You know that the language we are writing is not the one that machines can actually understand. We need to interpret/compile it (yup, Javascript is sort of compiled nowadays) and then execute it. We didn’t really care about it for a long time because that process was handled automatically by browsers for many years.

Things have changed in 2009. Ryan Dahl has written the first version of NodeJS and for the first time JS could have been run not only on the client but also performing operations on server. I have first time heard of NodeJS, when I was starting my journey as developer in 2013, I heard many voices saying (even after 4 years) that NodeJS (and its frameworks like express) won’t find it place competing against such solutions as .NET, Django, Ruby on Rails etc. It seems that it is completely opposite of the truth. You can go and check out:

And you’ll see that JavaScript repositories doubles Python by the number of pull request and is top popular language right now. Many of the most popular projects (based upon the number of forks and contributions) are also backed by JavaScript. JavaScript isn’t perfect, but sure it is popular! Now that we can run it on our mobile devices, use it to build apps, run it on desktop and tv, it can no longer be treated as “this funny language, to display time on your webpage”.

In this first episode, I’d like to ramp up the hype and actually build a little page and API endpoint using NodeJS and Express.

You can find the repository here:

To initiate the project type npm init and set the values as you please. You can just hit enter to go with empty/standard values. This should create package.json file in the root of your project. This file is like your command center. This is where you declare your dependencies and write scripts for your NodeJS app. Actually, let us start with writing one! In the root of your project create a src/server.js file as well as examples/basic.js. Let’s run some really basic JS code using Node. In basic.js we can write:

And add

"scripts": {
"start": "node ./examples/basic.js",
"test": "echo \"Error: no test specified\" && exit 1"
},

to your package.json. After that, if you’d like to run it type:

yarn start into the terminal while being in the root project of your application. Now we can run JS code without using the browser! Ok, let’s actually move to writing our server.

First will need some dependencies. Express is popular web framework that will help us set up the API and some server rendered pages with ease. Let’s add it to the mix:

yarn add express

You can see our first dependency popup in package.json as well as node_modules folder being created. You can open this folder and see dozens of folders. You see express package itself is dependent on other packages and those packages also have their own dependencies. So instead of getting just one folder we had to download whole dependency tree for express:

https://i.stack.imgur.com/8sTjA.png — Dependency tree

Ok, let’s try to fire up our server.js . At the very top write:

import express from 'express'

and in your package.json add new script:

"server": "node ./src/server.js"

And if we run this we will get:

Our first error

Why is that? Well, we are using ES6 import syntax, that’s not implemented into the NodeJS yet. There are two ways we could handle that. We could change our import statement to use require instead:

const express = require("express")

Or we could add Babel transpilator to make this syntax understandable for Node. Since I believe it’s good to stay ahead of the curve, we’ll use the latter.

To set it up we can take a look at https://babeljs.io and simply use the commands they’re showing on their main page:

yarn add --dev babel-cli babel-preset-env

They will pop up as devDependencies in package.json . To actually make Babel work we need to specify its configuration. We can do that by creating .babelrc file in the root of our project:

{
"presets": [
"env"
]
}

Now we are ready to finally transpile the ES6 syntax so that Node can understand it. Let’s change server script in package.json:

"server": "babel-node ./src/server.js"

Now we can run it and there are no errors! Ok we can actually create and run our server if we change our server.js code to:

Well, not really impressive, isn’t it? Let’s start by adding our first endpoint. It will be used to fetch users:

Take a look and familiarize yourself with the way we setup routes in our app. We use higher-order functions to do so. The name of the function is actually corresponding to the HTTP method you wanna specify for given endpoint. The first argument is the endpoints name you’d like to set and the second is a function taking req and res arguments. As you may guess those are abbreviations for request and response objects. For example, req object will contain fields like body or params. You can read more about it here:

To check whether our endpoints are working, I will be using POSTMAN. Now if we perform GET request pointing to localhost:4000/users we will get our users.

Users fetched

It’s not much and it’s not particularly very useful since they’re not being fetched from a database, but I promise will change that in future.

There are many shortcomings with how our app is set up. For example if we’d change one of the objects that we get app from our endpoint, we would have to stop the server and restart it, to actually see the change. We can fix this by adding nodemon library and changing how our scripts work:

yarn add --dev nodemon

Now we have the auto-reloading feature in place! Ok, to finish this first part I’d like to set up the views for our app. My main focus is to build an API, but it’s always nice to know how to use Node and Express to build a websites. I’ll be using pug as my template. It’s good and very readable solution, but you might wanna go with other solution like for example mustache. Simply add the pug to the project:

yarn add pug

We must change our app a bit to actually inform Express that we’d like to use pug and specify the locations where our views will exists

Here we are using one of many global variables provided by NodeJS __dirname, which is pointing to the path of the current file directory. As you can imagine this one is very helpful when working with directories.

Ok, to actually show the view to the user we must create the template and render it as a response to given request. Start by creating views/index.pug file with given content:

If you have encountered Python you should feel at home, because Pug also heavily relies on indentation to do nesting, which I personally very like. We can immediately see that h1 and ul are parallel because their indentation is the same. The li‘s are a children of ul because it’s indented further under ul. Also this means we don’t need closing tags for our markup.

You can also see that we are using = a lot. This enables us to build markup based on the data provided by Express. We simply tell Pug where we want to use variables passed into the view. Let’s actually set the Express route to use our view.

There’s one more very useful Pug feature that I’d like to show you. Let’s start by adding a footer to our current view:

Let’s add another view for example about page:

app.get('/about', (req, res) => {
res.render('about');
});

and after that we can define our about.page

You can clearly see a problem here. We have duplicated code for the footer markup. Thankfully using Pug, we can define partials/includes, which are components reusable across other views. We’ll define one for footer in includes/footer.pug and paste the contents of footer there. Watch out for indentations.

After that we can simply write in both of our views:

include ../includes/footer.png

Now we can change footer as we please and it will be updated on both views. We can also use conditionals to render some parts of markup based on variables passed from express. Also includes inherit the variable scope of the main views they are included into. Let’s change our routes a bit:

And after that we can use the boolean renderBetterFooter in footer.pug as it inherits it from about and index views:

There are many other really fun and useful concepts regarding Pug and I encourage you to check those out, but from now on I will be focusing on building the API.

Cheers and see you in next one!

--

--

Wojciech Bilicki

Mobile & FrontEnd Developer at OKE Software Poland. Marvel fan. Can't live without music and books.