How to use Nodejs - For Absolute Beginners (Part 3)

How to use Nodejs - For Absolute Beginners (Part 3)

Using NPM, Express, EJS and Basic Routing to build a Node App

NPM (Node Package Manager) is the coolest thing we may encounter with node. It helps us just type a bunch of text and download useful packages to make our app development faster. If you ever used composer with PHP, you would totally know how much a life saver npm is. We would get to using it shortly. Checkout your npm version, to be sure we have the big boy kicking, by typing the following npm -v in your command line/terminal.

Express is a node package for creating servers. It takes all the heavy lifting away from us and allows us have a fully functional server with just a few lines of code. Routing with express is a life saver. Without express, we would have been doing a lot of if…else just to create routes for our app. Now, we can simply just have get or post routes super easily. We’d see it shortly.

EJS (Embedded JS) is a simple templating engine that lets you generate HTML markup with plain JavaScript. If you come from PHP, you are probably used to having PHP code inside your HTML markup that allows you spit data out based on some of your predefined actions. Well, ejs does something similar for you as well. We would get to it very quickly soon.

To get started using express and ejs run the following code in your command line/terminal.

npm install express --save
npm install ejs --save

We use the --save flag to add the package as a dependency in our package.json file automatically. This makes it easy for someone who pulls in our app to simply run npm install and get all the packages we used to develop the app.

When you are done, check the folder containing the app. You would notice some addition - node_modules folder. Every node package we have to install will be found there. When we require the package in our app, node will quickly fetch it from there. Yep, it is that easy and we are about to make cool stuff with these packages. Shall we?

Go back to your code editor and create a file app.js if you do not already have it. If you do, clear everything in it and paste the below code there.

var express = require('express'); //pulls express into our app
var app = express(); //initialize express so we can use it
app.set('view engine', 'ejs'); //set our view engine to ejs - more on this
app.get("/", function(req,res){res.render("index")}); 
//our app listens for a url sent via get method and returns a view
app.listen(8080, 'localhost');
console.log("We are now listening on port 8080");

When we are using express, we need to set a view engine that express would use to render our pages. View engines allow us to define our web pages in different convenient formats that we could easily render. Before, we had to use file system fs to read the entire file into a variable then output that variable. That is a lot of work view engines take care of. We would learn more as we proceed.

Now, let’s create a folder named views. It is going to hold all our webpage files so our view engine can easily find them. Create a file index.ejs inside the **views** folder and put some HTML content in it. ofcourse, the extension of the file is .ejs because our engine is ejs. I used the content from the section on above. When you are done, serve the app using node app and check it out on the browser to see what we have done. Super cool right?

Let’s try something even cooler. Let’s create a contact page and have our app handle post data. I created contact.ejs inside my views folder and added a small contact form inside it. I’d share screenshots instead of the code so you can make your own and figure even more stuff out. Quickly grab a new package we would be using before continuing - npm install body-parser --save

You already have an idea right?

Here is how my app.js file looks like right now

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({extended : false});
app.use(urlencodedParser);
app.set('view engine', 'ejs');
app.get("/", function(req,res){
                res.render("index");
        });
app.get("/contact-us", function(req,res){
                res.render("contact");
        });
app.post("/contact-us", function(req,res){
                res.write("You have contacted us. Details are below");
                res.write("\nHi "+ req.body.firstname + ", you said:");
                res.write("\nMessage: "+ req.body.message)
                res.write("\nWe would use your provided email "+ req.body.email+ " to get back to you");
                res.end();
        });
app.listen(8080, 'localhost');
console.log("We are now listening on port 8080"); //Helps us know our app is actually running

Let me introduce our new friend body-parser - previously bundled with express but currently standing on its own, we use body-parser to read the content of a request body. See where we define app.use(...)? That’s us telling express to use body-parser so it will not tell us stories when we try to read post data sent to us. Yep, body-parser made it possible for req.body.firstname to actually return something rather than just turn up as undefined or even flag an error (it actually does without body-parser. You can try it and see).

When you visit our contact-us url, you would see the form to fill. I made my contact page to submit post data to contact-us url. I can now access that data using the post method. The rest of the stuff there are things we already did and are familiar with. When you run the page, you should see something like this

My output after filling the form

The final thing we are going to do here is turn our message into a template with ejs and then dynamically generate it for responses. Create a file response.ejs and add the following code to it

<html>
        <head>
                <title>Response - Node</title>
        </head>
        <style type="text/css">
                body{
                        margin:100 auto;
                        width: 50%;
                }
        </style>
        <body>
                <h1>Thank you for contacting us</h1>
                <h2>Hi <strong><%= name %></strong>,</h2>
                <p>We got the below message from you</p>
                <pre><%= message %></pre>
                <p>We are going to get back to you using your email address: <%= email %></p>
        </body>
</html>

To output data sent to our ejs template file, we use <%= some data name here %> and that does the trick. You can also execute javascript code inside the template file like the code below. Add it to your file and try it.

<% for(var i=0;i<3;i++) {%>
  <%= i %>
<%}%>

If you have come this far, congratulations! You have started with nodejs and now you know how to build an app with it. There is a lot not covered here as it is basic introduction to node, so do very well to read up more. From here at least, you should have an idea of what to figure out, right? Node is really neat and super fast, so you would want to learn all about it. Don’t stop here, try new stuff and keep learning. You’d love every step of it.

Happy coding !

Like this article? Follow @chiefoleka on Twitter