Skip to main content

Up and running Node.js

      What we are gonna do?

We will be creating a web app. A user can find gifs based on the word. To implement this we will be creating a backend service using Node.js, Express, and frontend using React. We will use Github for Source Code Management and finally we will deploy our project to AWS. We will also set up a pipeline for CI/CD (Continuous Integration and Continous Deployment).

Setup the development environment

This part you have to do on your own.

Fun part. Start coding.

Fire up the terminal if using ubuntu hit alt+ctrl+t.

Create a new directory for the project.

Image for post

Voila, npm will create a new package.json file.

Now let’s start writing code. We will use express for creating the backend server. Discussion about express is out of the scope for this post. Let’s pull express as a dependency from npm.

Image for post

npm will create a new package-lock.json file and node_modules directory.

Server

Writing and running the express server is pretty easy. Simply create a new file index.js and paste the below code.

var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Server is up and runnig on port 3000!');
});

Now let’s test our server. Run node index.js and visit http://localhost:3000/ to check your server in action.

Integrating with Giphy API

To integrate with Giphy we need GIPHY’s API. Go and create a new app in GIPHY and obtain the API key.

To make an API call to GIPHY API we need another npm package request and request-promise.

Run npm install request — save and npm install request-promise — save.

Once done. Let’s create a new API /gif. Update your code with the following snippet.

var express = require("express");
var app = express();
var request = require("request");
var rp = require("request-promise");
app.get("/", function(req, res) {
res.send("Hello World!");
});
app.get("/gif", async function(req, res, next) {
const options = {
uri: "https://api.giphy.com/v1/gifs/search",
method: "GET",
qs: {
api_key: "<API_KEY>",
q: req.query.search,
limit: 3,
offset: 0,
rating: "G",
lang: "en"
}
};
const response = await rp(options);
res.json(response);
});
app.listen(3000, function() {
console.log("Server is up and running on port 3000!");
});

Now restart the server. And the endpoint

http://localhost:3000/gif?search=shashi

And you can see the returns response from GIPHY’s search API. Now our backend is ready to deploy.

Deployment (Not a rocket science)

Prerequisites

All set?

Github

Let's initialize the repository, run git init.

Image for post

Create a new file .gitignore and paste the following content.

node_modules

Now run some more git commands:

git status

git add .

git commit -m “awesome commit message”

git remote add origin <YOUR_GITHUB_REPOSITORY_URL>

git push origin -u master

Provide your username and password.

At this point, you have successfully pushed your code to GitHub.

AWS Server

Login to your AWS console.

Image for post

Click on the Launch Instance button.

Image for post

Scroll down and click on the Select button for Ubuntu Server.

Image for post

Go ahead with the auto-selected t2.micro instance. Click on the Review and Launch button.

Image for post

3, 2, 1, and click on the Launch button.

Image for post

Choose “Create a new key pair” from the dropdown menu. Input the name. And download the key. It will download a .pem file.

KEEP THIS KEY FILE SAFE AND DON’T LOOSE IT. YOU WON’T BE ABLE TO DOWNLOAD IT LATER.

Image for post

Once you have downloaded the file. The Launch Instance button will be activated. Click on the Launch Instance button to launch a new instance.

Image for post

Awesome we have just launched a new AWS EC2 instance.

Navigate to Services -> EC2 to view the instance.

Image for post

Well done.

Now scroll to the right side and click on launch wizard.

Image for post
Image for post

Click on the Inbound tab on the down.

Image for post

Click on Edit

Image for post

Click on Add Rule

Image for post

Give Port Range as 3000 and select Source as anywhere and Save. This will allow our incoming traffic on our server on port 3000 from anywhere over TCP protocol.

Well done.

Now let's deploy our backend service on the EC2 instance. For now, we will do it manually.

Select your instance and click on connect. You will see instructions on how to connect to the EC2 server.

Image for post

Give the 400 permission to your .pem file.

sudo chmod 400 <KEY>.pem

Now we are ready to connect with our server using SSH. Execute the following command.

ssh -i <KEY>.pem ubuntu@ec2–13–127–93–105.ap-south-1.compute.amazonaws.com

Image for post

if prompted write yes and enter. You will be connected to your EC2 instance.

Image for post

Setting up the server.

Let’s set up our server to host our application.

sudo apt-get update

Install Node.js and npm.

sudo apt-get install nodejs

sudo apt-get install npm

Clone your repository.

git clone <YOUR_REPOSITORY_URL>

cd <PROJECT>

Install npm dependencies

npm install

Start the server

node index.js

Now go to <YOUR_EC2_PUBLIC_IP>:3000/gif

Woah you have deployed your application on the server.

Next, we have to do some more things.

2. Setup CI/CD pipeline for automatic deployment of our application.

Thanks for reading. If you have some feedback, please provide your response or reach out to me on Twitter or Github.

Comments

Popular posts from this blog

Track stock market information right in your Terminal.

     Introduction: As a developer, I love working with the terminal. The plain, simple, and in my opinion the best way to interact with the computer (also it makes you look geeky). I spent most of my time in the terminal. By now you must have guessed I am a huge fan of the terminal and terminal-based applications. Recently I developed an interest in stock markets and started tracking the stock markets. Since I love working with the terminal I decided to build a terminal oriented application that can help me to track the stock market. Inspir e d by  wttr.in  I build  terminal-stocks  which can provide the stock's current prices, historical prices, and global market summary. How to use terminal-stocks terminal-stocks  is available and can be used without installation. Get the current price of the stock. curl terminal-stocks.herokuapp.com/ITC.NS Current price of stocks You need to provide the ticker of the stock and terminal-stocks will give you the price information of the stock.  t

Free to use tools for maintaining your OpenSource projects

In this post, we will talk about how to effectively maintain your OpenSource projects using tools/softwares which are free to use for OpenSource and the public repositories. Over time, when the project grows you, need to set up a few tools which can help you maintain the project and automate the trivial tasks. 1. Setup CI/CD Having an OpenSource project to which you might b e  contributing just as a hobby, but doesn’t mean you don’t need to set up CI/CD pipeline. You don’t need to expend a single dime on servers or need to use cloud services to run your CI/CD. There are a lot of CI/CD tools available free for open source projects and public repositories. One such tool is  Travis CI  which you can use for setting up CI/CD for your project. Travis CI Travis CI You can run test cases and deploy code to your servers. Travis CI works great and easy to set up the CI/CD pipeline. 2. Code Analysis and Code Quality Maintaining code quality as the project grows can be very hard and time-consumi

Why I switched to Brave browser from Google Chrome.

  I have used Google Chrome for the last 5–6 years, Chrome was the perfect browser and it has many features like syncing everything across the platform and devices, bookmarks, history, lots of extensions, password manager, auto-complete, developer options to name a few. All of these in with just a Google Id. Google ecosystem is very rich and useful. So why I decided to switch to  Brave  browser after giving it a trial for a month. Although chrome has everything, there were few issues that led me to hunt for a new browser and finally switched to Brave. Why Brave? 1. Chrome hogs the RAM “Aw ,  Snap! Google Chrome ran out of memory while trying to display this webpage.” I am sure you might have seen this message. This message appears when chrome has eaten all of the available RAM memory. I understand the reason behind Chrome using a lot of memory because of its architecture. It runs all the tabs in a separate process so that it can provide isolation. Modern sites and designers/developer