INTRODUCING NODEJS/EXPRESS

·

17 min read

Introduction

Since the inception of Node.js (a runtime environment for executing JavaScript code) in the year 2009, it has garnered the interest of both JavaScript and non-JavaScript developers alike. This is not just a mere coincidence. One of the reasons this is so can be attributed to the fact that back-end development is no longer rocket science for front-end developers because JavaScript can now be used for both the front and back-end (using Node.js) of a web application. Another reason is that it is super fast and highly scalable - great for prototyping and agile development.

Now, let's dive into the basic fundamentals of Node.js and explore what you should know about this JavaScript runtime. Also, we will touch on the Express framework which makes it simpler to build web apps with Node.js. We will also look at the reasons for its popularity and finally, some building blocks of an Express application.

In this article, we will look at:

  1. An Overview of Node.js and Express Framework
  2. Introducing Node.js
  3. The Node architecture
  4. How Node.js works
  5. Installing Node.js
  6. Your first Node.js program
  7. The Express framework

An Overview of Nodejs/Express Framework

Node.js and Express are revered for their speed, flexibility, simplicity, and scalability. The Express framework is very minimal, liberal, and open-ended. It provides the mechanism to set web application settings like the port to use for connecting, request handlers for different HTTP verbs at different routes(URL path) MDN . Node.js is a superb solution for real-time web applications primarily because of its asynchronous nature, great performance, and design to optimize scalability and productivity.

Introducing Node

Node.js as it is formerly called is an open-source, runtime environment for executing JavaScript code on the server or outside of the browser environment. Oftentimes, we use Node to build backend services such as Application Programming Interfaces(API) and the backend of our web applications. It is ideal for building data-intensive, highly scalable, and real-time applications such as Chat Apps, FinTech Apps, Ecommerce Apps, Streaming Apps, etc.

Node has myriad benefits from a server-side perspective which include but not limited to:

  • Scalability and great performance. This is by far one of the most benefits of using Node in building your back-end service. Node.js is asynchronous in nature. What this means is that clients' requests to the server are continuously being processed without having the client to wait until the previously sent requests are processed. This explains why it is used by large companies like PayPal, Uber, Netflix, etc. to build the back end of their applications.

  • Since Node.js is written in vanilla JavaScript, less time is spent dealing with building your web application with different programming languages when building both the front and backend of your web application. This, no doubt allows you to maintain a cleaner and more consistent codebase using the same naming conventions, tools, and best practices.

  • Node.js is available on different operating systems such as Windows, Linux, macOS, etc. which makes it very portable and readily acceptable.

  • Another advantage of using Node.js is because it has the largest ecosystem of open source libraries available via NPM.

  • Since the event Queue and thread Pool is used in Node.js, multiple requests can be handled concurrently without hitch. In other words, Node.js enables the coherent handling of a large number of incoming requests.

Node Architecture

Basically, every meaningful thing we know has an architecture that explains in toto its fundamentals, dynamics, and structure. Let's consider a building for instance. A building has an architecture that explains the style, design, and method of construction alongside other physical designs.

Talking about Node.js, its architecture is single-threaded. The event loop allows it to handle loads of concurrent requests and returns the responses back to their corresponding clients. Let me quickly itemize how this works.

  • Firstly, clients send a request to the webserver either to query for data, update data, or delete data.

  • Secondly, Node.js notes the incoming requests and adds them to the Event Queue.

  • And lastly, the events are then passed one-by-one through the Event Loop which processes them and returns the responses to their corresponding clients.

How Node Works

Earlier I mentioned that Node applications are highly scalable, data-intensive, and offer real-time capabilities and this is because of their non-blocking, asynchronous nature. In Node, we have a single thread to handle all requests and functions. This asynchronous nature is expedient when working with Node.js because it ensures that the event loop is never blocked by a synchronous or long-run task/operation.

When a request is made, Node.js passes the request to an asynchronous function which does the work even though there is only one event loop. If the functions were synchronous in nature, then the event loop would get locked up or blocked with one client's request and response and the other clients would have to wait till that client was done.

When programming in Node.js, deliberate effort must be made to ensure that your functions are asynchronous, as it is also very important to catch errors on the server before it is passed back to the client. The reason isn't far-fetched. Doing this will prevent any error from getting to the event loop which could possibly crash the program.

Installing Node

Installing Node on your machine is pretty much easy. If you are on windows, open up your command prompt, and if you use a Mac, open up your terminal. First things first. Let's check if you already have node installed on your machine:

On your command prompt/terminal, run:

node --version

Screenshot (192).png

As you can see in the picture above, I'm running node version 12.18.1. In this tutorial, I'll run you through how to install the latest version of Node on Windows (for those using a windows machine) and on Mac.

How to install Node on windows

The first step in building any Node.js application is by installing Node on the client system. To perform the installation of Node.js on a Windows machine, follow the steps below:

Step1) Navigate to Nodejs.org in a web browser. Click the Windows Installer button to download the latest default version.

node-v.png

Note: There are other versions available. If you use an older Windows version, you may need to download the 32-bit version. Choose LTS (Long Term Support) if you are new to Node.js because it is less prone to bugs OR you use the top link to make a switch from the stable LTS version to the current version.

Step2)Once downloaded, double-click on the downloaded.msi file to start the installation. On the first screen, click the Run button to begin the installation.

1.png

Step3)You will be welcomed to the Node.js set-up wizard- click Next

Step4)Following that, you will be directed to review the license agreement. Click Next if you agree to the terms and conditions.

2.png

Step5)The installer will prompt you to choose a default location. Click Next if you're okay with the default location or change it if need be.

Step6)The wizard will prompt you to install some other components. Again, click on Next if you have no specific needs

3.png

Step7)Click on the install button to complete the installation

4.png

Verify Installation

To confirm that Nodejs was installed successfully on your Windows machine, open your Command Prompt and run the following code:

verify.png

Voila! That's it, guys. We have successfully installed Node on our windows machine.

Next, I'm going to show you how to install Node on Mac.

How to Install Node on Mac

Step1)Go to nodejs.org to start the installation process.

1886.png

Remember I mentioned that the LTS(Long term support) version is recommended for developers who are new to Node because unlike the Current Version, LTS is less prone to changes and bugs.

Step2)After downloading, locate the file on Finderand complete the installation process.

22.png

Step3)To verify if the download is complete, go to your terminal and enter the following command:

node -v

If a version was outputted, then you are all set!

Pretty straight-forward right? Next, we are going to write our first Node.js program. Ready for this? Now let's get started.

Your First Node Program

In our first Node.js program, we are going to create a simple Hello World using the following steps as guidelines.

Step1)Go to your command prompt (for Windows users) or your terminal (for Mac users) and type the following lines of code:

mkdir firstApp
cd firstApp

The first command will create a new folder inside the directory that you're currently in, mkdir = "make directory". While the latter, cd = "change directory", in this case, to navigate to the new dir firstApp

Step2)Still on your command prompt/terminal, let's initialize our project and link it to npm-acronym for (Node Package Manager) in our folder.

Npm is where all Node packages live. You can visualize packages as modules or more preferably bundles of code that carry out a specific function. It is these functionalities that we utilize as developers when building an application.

Run:

npm init

Running npm init creates a package.json file in our firstApp folder. This file contains references to all npm packages you will download for use on your application. The command will prompt you to enter a number of things. You can enter your way through all of them except this one below:

entry point: (index.js)

You will want to change it to:

app.js

Step4)Install Express in the firstApp directory Go to expressjs.com

N.B: We will talk about Express in-depth in the subsequent sub-heading.

The Express framework

While still in the firstApp directory, run:

npm i express --save

The install command we just ran will find the express package and install it to your project. You should see a node_modules folder created in the root of your project(firstApp). The addition of --save will save the package to your dependencies list, located in the package.json, in your firstApp directory.

Step5)Next, go to your preferred text editor and create a file- let's call it app.js

Inside app.js, write the following lines of code:

const express = require ("express");
const app = express();

app.get('/', (req, res) =>{
res.send("Hello Peeps!");
});

app.listen(6060, function () {
  console.log('Example app listening on port 6060!');
});

Let's quickly explain the code snippet above.

In the first line, we loaded our express module by using the require function which returns a function called express. In line two, we called the function like this express() which returns an object of type express. By convention, we call this object app and we stored the result in a const app. Note that both line 1 and 2 represents our application. Also, this app object has a bunch of useful methods such as: app.get(), app.post(), app.put(), app.delete()

In line 3, the app.get method that we used takes two arguments: the first is the path or url and we used / to represent the root of the URL while the second is takes a callback function req, res which will be called when we have an HTTP get request to this endpoint /.

The listen method starts a server and listens on port 6060 for connections. It responds with “Hello Peeps!” forget requests to the root URL (/).

Step6)Run the app Now to run the app, go back to your command prompt/terminal, and run:

node app.js

Last and final step. After running the app, head over to your preferred browser and load localhost/6060 to see the output. You should see:

Hello Peeps!

Conclusion

Since Node is known for its flexibility and scalability, it is only ideal that frameworks associated with it should have similar features and this brings us to the Express framework.

According to Express documentation, Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It contains myriad of HTTP utility methods and middleware at your disposal for creating a robust, quick and easy API. It also provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love and more importantly, many popular frameworks such as Kites, Nextjs, Kites, Locomotive, Sails, Poet, etc, are based on Express.

With the Express framework, there are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and a host of many others. Click here to find a list of middleware packages maintained by the Express team, alongside other popular 3rd party packages.

RESOURCES

Find this article useful? Kindly like/leave a comment.

Thanks for reading

.)