Creating your first NodeJs App

saroj990

saroj sasmal

Posted on June 20, 2022

Creating your first NodeJs App

Introduction

NodeJs is an open-sourced, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.

If you're looking for an article that gives you basic understanding of NodeJs application, you are at the right spot.

In this article we are going to take a look at the following things.

  • NodeJs and Node Package Manager.

  • A very simple server built using NodeJs.

  • How to use Express framework

NodeJs is a javascript runtime built on top of Chrome's V8 engine that leverages the option of writing javascript code on server. We can think of runtime as similar to an environment which can be used for executing code written on a specific language.

Before the inception of NodeJs, we could only write server side code using languages like Ruby, C# with .NET or Java.

NodeJs made thing easier for developers so that we don't need to know two different languages any more of building a full-stack application.

One of the cool thing about NodeJs is that, it is asynchronous from the ground up, meaning you never ever wait for anything while making I/O operations.

I/O operations are the operations that deal with the input/output system. Here is a few examples.

  • Operations with Disk

  • Interaction with Network(http)

  • Database Operations

Alt Text

Most of the I/O operations are asynchronous by nature and handled by the Operating system pretty well.

For I/O operations, you don't ever wait for those operations to be completed for performing other operations, all you need to do is just attach a callback function, which is basically a function that can be passed into another function and when the I/O operation is done, whatever we put inside that function, gets executed.

Let's take a closer look at following code to understand the I/O operation.

fs.readFile('users.txt', function(err, result) {
// callback function called when the file is read.
  if(err) {
  // handle the error
  } else {
  // perform some operations with the result
  }
});

// other operations
for(i=0;i<5; i++) {
  console.log("i = ", i);
}
Enter fullscreen mode Exit fullscreen mode

fs.readFile may take a bit of time to read the content of the file based on the file size, but when the file reading operation is done, it simply calls that callback function.

Interesting to notice that while the file is being read, the control does not stop here, rather jumps over to the next line of code which is a for loop in this case and starts executing the code. When the file reading operation is finished, it executes whatever is there inside the callback function. This is what we call asynchronous programming.

Let's start building something real, It completely fine if things don't make sense at this moment, things will more easier to understand as you move forward with developing application from the scratch.

NPM(Node Package Manager)

npm is the package manager for NodeJs.

we can use it to download and use package hosted in the npm registry system. There are tons of libraries hosted on npm. We can add the dependencies from here based on our requirements.

To start off an application, we need to run the command npm init. This initialises the application by creating a package.json file in the root directory of the application.

package.json is a configuration file that store meta data about the application for example author, name of the project, dependencies, script to run and build application etc.

How to install a dependency using NPM.

To search for a specific package, visit npm registry, take a look at the npm module, it's number of weekly downloads and last commit etc. But if you know the name of the package, then most of the time you can simply run npm install.

npm install express
Enter fullscreen mode Exit fullscreen mode

What is express ?

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Let's try to understand why do we need express in the first place. In order to understand that we need to create an http server using Node.

var http = require('http');

// create a server
http.createServer(function (req, res) {
  // http header
  // 200 - is the OK message
  // to respond with html content, 'Content-Type' should be 'text/html'
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('Node.js says hello!'); //write a response to the client
  res.end(); //end the response
}).listen(9000);
Enter fullscreen mode Exit fullscreen mode

So with these 5 lines of code, we were able to create an http server and send text response back to the browser. But it becomes really difficult and hard to maintain the code by ourselves, when we start adding complex features like routes, template engines and middleware etc.

To make this thing little easier for us, we have a web framework i.e, express built on top of NodeJs that packages a few necessary modules together like router, middlewares and have features for error handling and debugging etc.

If this terms doesn't make any sense at this point, don't worry! once you start writing applications using NodeJs, You will have a better understanding of it.

Before you go ahead with the following steps, you need make sure that you have NodeJs installed on your machine. I am using an ubuntu machine and have both of them installed already. But if you have not done that yet, please visit here.

Okay Let's start doing some real coding!!

STEP-1:

Create a directory named 'express-app' somewhere on the computer. You can do it from UI or can use command line for doing the same. I use an Ubuntu machine and love working with command line.

mkdir 'express-app'
cd express-app && npm init
Enter fullscreen mode Exit fullscreen mode

and hit enter till the end, it is going to create package.json file in the root directory.

STEP-2:

Create a file that would act as the starting file for this application, usually people name it, server.js or index.js. Let's call it server.js. Open up server.js file with your favourite editor, we are going to write some code here.

const express = require('express');
const app = express();
const port = 3000;

// this is a route
app.get('/', (req, res) => res.send('Hello World!'));

app.listen(port, () => console.log(`server is listening on port ${port}!`));
Enter fullscreen mode Exit fullscreen mode

So we can run the file with node server.js being on the same directory.

node server.js
But wait! we're getting some error here, which looks something like this.

module.js:549
throw err;
^

Error: Cannot find module 'express'
at Function.Module.\_resolveFilename (module.js:547:15)
at Function.Module.\_load (module.js:474:25)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
Enter fullscreen mode Exit fullscreen mode

And the reason for this is that fact that we are using a module i.e, express but we haven't installed it yet into our application. Let's do that now.

npm istall express or npm i express
Now run the server.js file with node server.js command. You will see, that something just got printed onto the console.

Hurrah!!, You just created your first server and if you open up a browser tab and hit this URL http://127.0.0.1:3000 . The browser tab says Hello World.

Isn't that cool :). Just 5 lines of code and your server is up and running.

Now let's add a route that will serve an html file or a template from the server.

// server.js

const express = require('express');
const app = express();
const port = 3000;

// this is a route
app.get('/', (req, res) => res.send('Hello World!'));
app.get('/index', (req, res) => {
  res.sendFile(\_\_dirname + '/index.html');
});

app.listen(port, () => console.log(`server is listening on port ${port}!`));
Enter fullscreen mode Exit fullscreen mode

Let's create an html document called index.html inside the root directory of the project.

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
    Hello Express
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now pull up a browser tab and hit http://127.0.0.1:3000/index and there we go, we made it serve an html file from our server.

Now let's try something like sending some dynamic data from server that we can pass in into our view. In order to do that we need to integrate a template engine into our application. A template engine is a module that has its own DSL for writing HTML code and it can be compiled within server and sent back to client.

Here is a list of template engines that really plays well with NodeJs

Jade
Vash
EJS
Mustache
Dust.js
Nunjucks
Handlebars
haml

I like Handlebars the most, because it's syntax is pretty much similar to HTML syntaxes but it's my personal preference, if you feel like other templating engine works best for you, feel free to try it out.

If you want to get some more information on this Handlebars package, please visit here. But be sure you return this to this blog post :).

Okay, with all that said, it's time to do some hack with handlebars, let's try to integrate it with our application.

npm install express-handlebars
We need to make some changes to our server.js file to tell the application that we will use handlebars file as template engine.

// server.js

const express = require('express');
const exphbs = require('express-handlebars');
const app = express();

app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

const port = 3000;

// this is a route
app.get('/', (req, res) => res.send('Hello World!'));

app.get('/index', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// render home.handlebars when /home url is requested
app.get('/home', (req, res) => {
  res.render("home");
});

app.listen(port, () => console.log(`server is listening on port ${port}!`));
Enter fullscreen mode Exit fullscreen mode

So first we included the handlebars package and then specified to use express-handlebars module as the app engine, so that whenever a handlebars file is encountered, the handlebars module to take care of compiling that template. Next we set the view engine to handlebars so that the handlebars engine gets to know that whenever a '.handlebars' extension is encountered, it makes that to go through the handlebar engine.

Towards the end just before app.listen, we added another route that says to render home. This means when a request comes with /home, it will try to find a home.handlebars template and whatever is inside it, it will compile and send that to client. But one thing to remember here, that we need to have a views directory in the root directory.

views
--> layouts
--> main.handlebars
home.handlebars

The main.handlebars is the layout file for our application, well, this is not always necessary but most of the cases, you will need it, so that other pages of your application will inherit styles from it for example sidebar, header etc.

// main.handlebars

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>NodeJs App</title>
</head>
<body> 

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

The home.handlebars just need to contain the content that we want to show when someone visit this page. The content will be injected directly to the body of main.handlebars.

//home.handlebars

<div>
  Home sweet home!!
</div>
Enter fullscreen mode Exit fullscreen mode

Now let's try to pass dynamic data to our view. We need to add the following route to your server.js file.

app.get("/user", (req, res) => {
  res.render("user", { layout: false , user : 'john'});
});
Enter fullscreen mode Exit fullscreen mode

We need to create a user.handlebars file inside the views directory.

//views/user.handlebars
Hi {{ user }}, How are you?.
Enter fullscreen mode Exit fullscreen mode

We are simply passing a variable named user and using the double curly brace syntax to render that inside our view. Please checkout this repo for source code.

I think this is it for this article, I hope this blog post was bit helpful to get some basic understanding of NodeJs and Express. I would really appreciate and love to have your comments, questions on this. Till next time, keep exploring.

πŸ’– πŸ’ͺ πŸ™… 🚩
saroj990
saroj sasmal

Posted on June 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related