How to Build a Node Application Using a Pug Template

Primerose Katena
Bits and Pieces
Published in
6 min readMay 25, 2020
Image by Free-Photos from Pixabay

Introduction

In this tutorial, I will explain how to use a pug template and NodeJS to build a web page. We will create a Node application from scratch, set up Nodejs, express, and a pug template engine. At the end of this tutorial, you would have created an single web page and learn how to use the technologies mentioned above.

Prerequisite

To get hands on experience with this article you need to have:

  • Nodejs on your machine. Click here to get Nodejs if you do not have one.
  • Basic understanding of Nodejs.

In addition to the prerequisite mentioned above, you must be familiar with JavaScript. Start by creating a folder in a directory of your choice using the terminal. I named mine newProject :

mkdir newProject

Use the IDE of your choice, in my case I am using Visual Studio Code. Open the folder newProject in Visual Studio Code (VSCode). I recommend using the terminal in vsCode because it is easier to access, you do not need to enter the path directory. By running the code below, we initiate our project by creating a package.json file.

npm init

As shown below, I did not change anything except entry point , I changed from index.js (default) to app.js . However you can specify all the fields, read more about the content of the package.json fields here to make informed changes.

package name: (newproject)version: (1.0.0)description:entry point: (index.js) app.jstest command:git repository:keywords:author:license: (ISC)

The dependencies

You have successfully created a package.json file, located in the root folder of your project, for project identification and contain dependencies we will install add. Every dependency you add in this project will show in the package.json file. Let’s install Nodejs and other dependencies we need in the project, once it is done running it adds node modules folder and package-lock.json file:

npm install nodejs express

The dependencies we just installed serve different purposes. Express is a middleware web framework that handle routes, requests and responses.

We are ready to start! Let’s create the app.js file in the root folder. In this file, we create an HTTP server and it listens on port 3000.

The web server

const express = require('express')const app = express()app.listen(3000, () => console.log(“Listening on port 3000”))

Output:

Listen on port 3000

Nodemon

We executed node app.js in the terminal to get this output. It is not an efficient way to develop Node applications because each time we make changes, we have to stop the webserver, save changes, and execute the same command. Nodemon automates the process of restarting our Node project each time we save changes.

npm install nodemon

Once done installing, go to the package.json file and add the following under script:

scripts{

"app" : "nodemon app.js"

}

You can name your key value to anything, in my case I named it app. To execute our Node application using Nodemon, you type in the command line:

npm run app

From now going on, all you can do is to save all your changes and let Nodemon takes care of restarting the web server for you.

The npm start

Use of start as a key for our entry point of the application can simplify our lives. When Node observe start, it will automatically execute the value associated with it, in my case nodemon app.js . It is highly recommended to use start because someone who will clone your repository will not struggle to go through your code to find the entry point, since npm start is a standard. Let’s go back to the package.json file and change the key from app to start .

scripts{

"start" : "nodemon app.js"

}

When we use start , we can gracefully omit run command in the command line interface and Nodejs will understand.

npm start

Here is the output you should be expecting since we introduced Nodemon.

> newproject@1.0.0 start /Users/mac/Documents/newProject> nodemon app.js[nodemon] 2.0.3[nodemon] to restart at any time, enter `rs`[nodemon] watching path(s): *.*[nodemon] watching extensions: js,mjs,json[nodemon] starting `node app.js`Listen on port 3000

Adding the PUG template engine

Here we could use HTML or any front end framework of your choice. In this tutorial, we will explore using an HTML template engine, Pug, which works very well with Node.js. Pug template engine allows us to write code that can be converted into HTML code. One of the major noticeable differences between HTML and pug template is that, a pug template does not require the closing of tags. The other interesting thing to note about Pug template is that, it has conditions, loops, and other features HTML does not have. It’s time to create our own Pug file.

Installing PUG

Let’s install PUG in our Node application as a dependency.

npm install pug

Let’s create our own Pug file to fully understand the Pug template. In the root folder, create a folder called src. Within the src, create a folder called views. In the views folder, we create a file called index with an extension called .pug. You will notice that your Pug file has a red icon. Let’s add code to our index.pug file.

Doctype html  html     head        meta charset UTF-8        title Exploring the Pug template     body        h1#myHeading This is a pug template        p.firstParagraph I love this template!!!

Indentation is very crucial in Pug, it makes it easy for Pug template engine to know which part of the code is nested. In the code above note how I added an id called myHeading to h1 and class to a paragraph. When code above is compiled, this is what it translates to:

<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>
Exploring the Pug template
</title>
</head>
<body>
<h1 id ="myHeading" >
This is a pug template
</h1>
<p id = "firstParagraph">
I love this template!!!
</p>
</body>
</html>

The next step is to add our template, pug. In the app.js , let’s add the pug file. Using app.set(), we specify that we are using a view template engine called Pug and specify the directory our index.pug is located. Using app.get(), we render our index.pug file.

const express = require('express')const app = express()app.set('view engine', 'pug')app.set('views', './src.views')app.get('/', (req,res) => {res.render(index)})app.listen(3000, () => console.log(“Listening on port 3000”))

Let’s run npm start on the terminal or just save everything if the web server was still running to check the output. Go to your browser and open http://localhost:3000. If you have carefully followed this tutorial you will see that our index.pug has been successfully rendered as shown below:

Conclusion

In this tutorial, you successfully created a Node.js application from scratch and learned how to integrate the template engine in Nodejs. You explored how cool this template engine PUG is, the integration of Node.js, and express as well as other dependencies.

Publish and Reuse React Components with Bit

Publish reusable React components from any codebase to a single component hub. Use Bit to document, organize, and even keep track of component updates and usage.

Share components with your team to maximize code reuse, speed up delivery and build apps that scale.

Example: exploring React components published on Bit.dev

Published in Bits and Pieces

Insightful articles, step-by-step tutorials, and the latest news on full-stack composable software development

Written by Primerose Katena

Project Manager || Product Manager || Product Operations and Strategy|| Email: katenaprimerose@gmail.com

Responses (2)

What are your thoughts?

Little correction..
change res.render(index) to res.render('index')

--

Great intro article thanks. I am a C# learning Node.js and this a helpful.

--