Tags

Node.js

Points to Note: Throughout this article all JavaScript code would be written following the ECMA-script 2015 standard. It would be nice if you had prior knowledge of JavaScript and Es6, yeah I know NodeJs Is so hot you want to get started immediately, but you know what lets just have a prerequisite tab;

Prerequisites:
1.Knowledge of JavaScript
2.Knowledge of EcmaScript 2015, commonly referred to as ES6 
3.Curiosity about NodeJs is and how it works
4.Enjoy writing hello world programs in JavaScript (LOL)
5.Have NodeJs Installed
6.Have Postman Installed

Okay, prerequisites aside let’s start digging. First we would want to make a clear distinction between what NodeJs is and what it is not. Read through this conversation between some friends and see if you could figure who was right:

Mark: Hey David what language is this?

David: Hey Mark this is NodeJs.

Mark: Is it a new JavaScript framework?

David: Ohhh yeah, it’s a new JavaScript framework or should I say, maybe it’s a library though not sure but it was originally written by Ryan Dahl in 2009, about thirteen years after the introduction of the first server-side JavaScript environment, Netscape's LiveWire Pro Web. The initial release supported only Linux and Mac OS X. Its development and maintenance was led by Dahl and later sponsored by Joyent and then the open source community....bla-bla-bla

Steve: Google Searches But I just saw from Google now that NodeJs is a run time environment and is neither a framework or library, but then what does it mean by NodeJs is a runtime environment?

David: urhmmmmm, well I don’t know, you know what, let’s call Johnson and ask him.

*Now that's my cue as Johnson to blow their mind.*

NodeJs is neither a library or a framework, but a run time environment. For people wondering what a runtime environment is, I would use an example from our not too distant relative java. Before running your code in Java and compiling, you need a Java Run time Environment (JRE) which comes most time packaged in a Java Development Kit (JDK), without this tools installed on your system you might not be able to compile and run your well written, sweet Java code. In essence the (JRE) makes it possible for us to run Java programs on our system, the same applies to NodeJs, Javascript as we knew then runs only on browsers, but NodeJs makes it possible for us to run our Javascript program on our PC’s infact helps us run javascript outside the browser. To see what I mean before you install NodeJs on your system, fire up your visual studio code write a single console statement and try running it, yeah sure you should see an error, now install NodeJs and reload your vscode and try running the same program again, what happens it builds.

Now believing we have established what NodeJs actually is, we won’t fail to mention that NodeJs run on chromes V8 engine. V8 is the JavaScript execution engine which was initially built for Google Chrome. It was then open-sourced by Google in 2008. Written in C++, V8 compiles JavaScript source code to native machine code instead of interpreting it in real time.

Okay, back to the business of the day, creating a Node API.

Creating a Simple Restful API With NodeJs AND ES6

First we would need to install Nodejs on our system, if you haven’t done that yet.

Download NodeJs ???? Here.

After installing fire up your code editor let’s start creating our api.

Create a project directory, I named mine nodeApi

Create an index.js file in your project directory

Open your command window and navigate to your project directory, or should I say CD into your project directory

Once in your project directory, run npm init, you can click enter through out all the prompts and have npm setup your project with the default settings or you could edit things like author and description, you can edit later after this part when your package.json file is created.

After the step above, check in your project folder, a new file package.json has been added, you can make those changes as discussed above in this file.

Now lets get to writing our API. NodeJs has a built-in module called HTTP, which allows NodeJs to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method:

In your index.js file type the following;

const http = require('http');
const port = 3000;
const hostname = '127.0.0.1';

const server = http.createServer((req,res)=>{
    res.statusCode = 200;
    res.setHeader('Content-Type','text/plain');
    res.end('Hello World\n');
});

server.listen(port,hostname,()=>{
    console.log(`Serving running at http://${hostname}:${port}/`);
});

SO from the above ?? we would use the createServer method from the http module to create a Http Server. The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 3000. The function has two parameters, req and res, representing request and response respectively. Save the code, go back to your command prompt and use this command to run our project, node index.js.

Now our server is listening on port 3000, copy that URL on your prompt to your browser or postman and send a request to it, you should see the following;

Creating a server on node and making it listen for request is actually easy. Now lets create endpoints the users of our applications would use for communication with our system. This also is easy, type the following code into your code editor;

const http = require('http');

const server = http.createServer((req,res) => {
    if(req.url === '/'){
       res.send('Welcome');
    }

    if(req.url === '/courses'){
       res.send('welcome to courses');
    }
});

server.listen(3000);
console.log('Server listening at port 3000...');

On creation of the server, we listen to requests on our endpoints and when a request is made we check the re.url to determine what response the system should give. Yet again fire up our server and this time send request to this endpoints on postman http://127.0.0.1:3000/ and http://127.0.0.1:3000/courses, you should see what we sent as response that is welcome and welcome to courses respectively.

But then creating Endpoints this way would be very untidy and hard to organize, plus the chance of getting lost in your code is high, that's where expressJs as a framework built on top of NodeJs comes to play, there are other frameworks like, sailsjs, Koa, etc.

Go back to your command prompt and install express using this command 
npm install express --save, then enter


Now to use express we would have to import it and then use some of the methods that come shipped with it to create endpoints.

Type the following code into your editor;

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


app.get('/', (req, res) => {
  res.send('Welcome');
});

app.get('/courses', (req, res) => {
  res.send('welcome to courses');
});

const hostname = '127.0.0.1';
const port = 3000;
app.listen(port, () => {
  console.log(`Serving running at http://${hostname}:${port}/`);
});

Now that's how easy it is to write an API endpoint with NodeJS. When you are done typing the code, run it the usual way node index.js, look at the code and try making sense out of it. Have any questions please do drop them at the comment section.

For further Readings i would recommend the following articles: 
1.NodeJs By w3 Schools
2.NodeJs by Moz Dev Net, a tutorial i also contributed to.


Guest Blogger

emmawedekind profile


Special thanks to our guest blogger Johnson Ogwuru, a Software Developer for his contribution to the Ronald James Blog this week.

twitter Johnson Ogwuru github ogwurujohnson 

Who Are Ronald James?

We are a leading niche digital & tech recruitment specialist for the North East of England. We Specialise in the acquisition of high-performing technology talent across a variety of IT sectors including Digital & Technology Software Development.

Our ultimate goal is to make a positive impact on every client and candidate we serve - from the initial call and introduction, right up to the final delivery, we want our clients and candidates to feel they have had a beneficial and productive experience.

Contact our Team

If you’re looking to start your journey in sourcing talent or find your dream job, you’ll need a passionate, motivated team of experts to guide you. Check out our Jobs page for open vacancies. If interested, contact us or call 0191 620 0123 for a quick chat with our team.

Let's be Friends!

Follow us on our blog, FacebookLinkedInTwitter or Instagram to follow industry news, events, success stories and new blogs releases.

 

 

Back to Blog

</Follow Us>