NodeJS – Kickstart

In this tutorial i am gonna talk about Node.js so that you will kick your engine to start developing Node.js Applications.

After this lesson, you will be able to:

  • Install Node.js.
  • Create Node.js webpage.
  • Understand Node.js basics.
  • Understand how data is sent to the server.
  • Understand to write Node.js websites.
  • Create Node.js Modules.
  • Create Node.js Package.
  • Create package.json file.
  • Create account in node package manager.
  • Publish the package.
  • Install and use the package.
  • Uninstall the package.
Estimated lesson time: 2 hours 45 minutes

Before you begin

You must have some understanding of web development and specially for Node.js . But do not worry i am here now we will talk about nitty gritty of essential components of Node.js.

Getting started with Node.js

The back bone of Node.js is Google Chrome Javascript runtime for building easy, fast scalable network applications. The platform is perfect for real time data driven applications because for applications that runs across distributed devices needs efficiency and lightweight non-blocking I/O model.
Node.js uses Google’s V8 virtual machine to interpret and execute your javascript code.

Installation

First, install the latest stable version of Node.js, download the version for your machine from Nodejs.org and run the installer. You will find the primary executable node.exe in the installation folder.

To verify that Node is set up correctly, by typing the below commands on the command line. This should output a version number:

C:> node -v

Creating Hello World from Node.js

After the installation has been done successfully, now you are able to write your first ever NodeJs application. Nothing is better getting starting with “Hello World” app. It’s kind of mandatory saying hello to the world before you ever jump in to something (kidding). So without further a do lets do this…

Open up your favorite text editor you wanna write into and write the following script:

var http=require('http');

http.createServer(function(request, response)){

response.writeHead(200,{'Content-Type':'text/plain'});

response.end('Hello World ! n');

console.log('Request Handled');

}).listen(8080,'localhost');

console.log('Server Running !!'); 

This is pure javascript, As you are going to make HTTP request from Node.js you need handler for that, so we need to include the http module. The http module is core built-in, low-level module that is highly optimized for performance.
With the help of http object we create a server object. the creatServer function takes the anonymous function as a parameter and has request and response objects. For the sake of simplicity i am using just the response object. This example does nothing with the request object (will talk later). Using response object to write the write HTTP header in which 200 means success and plain text content type means just to tell the user format of the response gonna write in the browser. The next line respond with the ‘Hello World’ and ‘Request Handled’ message is send to the console window. After when the createServer object is created it calls the listen function with port number and IP address, in this case it is our local server with IP 127.0.0.1. The last console message to assist the user to write on the console that server is running at the moment.
Save the file with ‘any-name.js’. After you save the file run the following in command prompt to start running your server.

C:NodeExamples> Node any-name.js

Quick Info: Change your directory path in which you saved the file  
 C:> cd path 


Leave the command prompt open and open any browser and hit

http://localhost:8080/

Request has been made from your browser to the newly created server (on command prompt) you can see the response sent back from the server. Response will be writing on the browser window and similarly you can see the command prompt for log text which says :

Server Running !!
Request Handled

Yupee !! Congratulations, you have written you first Node.js website and successfully running.
You can refresh the browser window to send another request to the server and server responds with same string and will be display on the browser.
Press Ctrl+C to stop server.

Personalized Response

As you have said Hello to the whole world, now you want to say hello to the specific person who hits your server.
Next example listens the request come from the users and say hello to them. Of course, the next thing we want to do is to process the request data to produce a response based on the request.

Same as for HTTP request we included HTTP module, for request base response we need to parse the QueryString for that we require URL module which provide help for parsing the QueryString. Url object has a parse method that accepts the actual URL, and second parameter value of true parse the QueryString.

var http = require('http');

var url = require('url');

http.createServer(function (request, response) {

var parsed_url = url.parse(request.url, true);

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hello ' + parsed_url.query.name + '!n');

console.log('Request Handled for ' + parsed_url.query.name);

}).listen(8080, 'localhost');

console.log('Server Running !!');

Save the application in ‘hello_asim.js’. Run the application and start the browser to hit the following url:

http://localhost:8080/?name=Asim

When the request is recieved successfully, you can see the response on the command prompt with something like this:

C:NodeExamples> node hello_asim.js
Server Running !!
Request Handled for Asim

And on browser window, you will see something like this:

Hello Asim
Quick Info: Return status codes:
■ 1** Informational Message
■ 2** Success
■ 3** Redirect
■ 4** Client error
■ 5** Server error

Create a Node.js Module

When ever you write code it’s best to reuse the code where possible. For usability perspective in Node.js we create modules. Module are single entity that can hold some functionality and can be reuse.
In the previous examples, require function were used to load module, which provide code reuse when developing Node.js applications. So you can create module by wrapping your code in a function and exporting it so it can be called from other code.

var http= require('http');

var url= requrie('url');

function anyFunction(){

http.createServer(function (request, response) {

var parsed_url = url.parse(request.url, true);

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Hello ' + parsed_url.query.name + '!n');

console.log('Handled request for ' + parsed_url.query.name);

}).listen(8080, 'localhost');

console.log('Server running !!');
}
exports.start= anyFunction;

In the example, code is wrapped with in a function. At the very last line, function is assigned to start property of exports object.
Save the code in ‘any_name.js’ file, and your module is created.

Create another file ‘index.js’ in which you will gonna include your newly created module and execute it, by using the require function. Enter the following code in ‘index.js’ file

var hello= require('./any_name.js');
hello.start();

The module is ‘./any_name.js’. As this is relative path that’s why we use ‘ ./any_name.js ‘ . The require function return the object that is assigned to the hello variable, and then the start method is executed.

Run the following code using command prompt.

C:NodeExamples>node index.js

This code works the same way as ‘hello_asim.js’ but this time it uses your new module.

Creating Node.js Package

Package is actually your application, it is basically the collection of your modules. Packages have dependencies over other modules and can be available publicly for others to use. You will use node package manager (npm) for publish your package or to install others package.
Package folder contains bin, and lib sub folders this is actually the typical hierarchy of the Node.js Package. With one package.json file with ReadMe.md.
bin folder contains the entry point for your application and lib folder is used for the modules files.

Practical example:

First create the following directory structure:

 packageName
     bin
     lib

Create the first module and save this to the lib folder with file name “counter.js” file name

var count=0;
function counter(){
      ++count;
      console.log(count+" Call(s) are made !");
}
module.export= counter;

First we have a count variable with counter function that will call each time you will made any call. export property of module, exports the function for the modules that wishes to call the function counter.

A next module with basic mathematics consider it as a module and save into the lib folder.

var counter = require('./counter');
function add(x, y){
counter();
return x + y;
}
function subtract(x, y){
counter();
return x - y;
}
module.exports = {
addition: add,
subtraction: subtract
}

Save this as math.js. In the newly created module in lib folder, we just reference the counter.js module so that we can use their exported function from here. As the counter module is present is the local module and present in the current folder of the package so that is why we use this ./counter.js syntax. The reference is assign to the variable counter with the help of this we can access the methods of the counter module. As counter() has been called from the add and the subtract function. From the other math module.
Same as for the math.js the two add and subtract function are exported with the help of object. Like if there is a situation where you need to export two or more function for the others modules to use, you must need to create the object for that. In this example addition represents the add function and subtraction represents the subtract function. Method name must not to be same as the function name. This won’t be necessary. You can give any method name to that.

Creating External module

After the all the modules is created, then you must need one entry point for your package so that others outsiders can access your whole packages functionality from one gateway. so for this we need to create the main.js file that can access the whole package.

var path = require('path');
var fs = require('fs');
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
var math = require(lib + '/math.js');
module.exports = {
addition: math.addition,
subtraction: math.subtraction,
}

Save this file as main.js in the root folder.
In this module, path and fs these are the build in packages in Node.js helps us to get the path of the lib folder. These are basically helpers. Then refer to the math.js using this path.
At the end module.export assigns the object a two function that we need to exported by the package.

Creating the package.json file

Now it’s time to publish your package for the use. First you need to create the package.json file of your package so that it will become easier for the node package manager to publish your package into npmjs.org
Node package manager is already installed when you install the Node.js for quick check you can see the version number:

C:mypackage> npm -v

Type the following to generate the package.json of your package

C:mypackage> npm init

It will ask you for the values for the keys.
At the end package.json would look like this

{
"name": "mypackage",
"version": "0.0.0",
"description": "My first package",
"main": "bin/main.js",
"repository": "",
"keywords": [
"math",
"addition",
"subtraction",
],
"author": "khawaja Asim",
"license": "AFL-1.1"
}

Create account

Once you have done with the package.json file it’s time to publish the package but before going for the publish create the account in the npmjs.org manually or you can create account using the cmd node package manager. Type the following to add new user:

C:mypackage> npm adduser

Once you created the account now are able to publish the package.

Publish the package

As your package.json file is ready and you are already logged in. You are all setup for going for the publish. It’s time for the world to see your talent, it’s time for the world to see your first ever package you have developed. It’s time to get the applause 😉

Type following in the cmd to publish your package. Remember you must be in the root where package.json file is saved and others package folders.

C:mypackage> npm publish

Install and Use the package

As your package is published you can install and use your package now. You can install the package globally or local for specific application. Installing package globally gives all the application same version, whereas for locally installed you must have to install for each application and same for the updates.

To install the package locally

C:installedpackage> npm install mypackage

For globally:

C:installedpackage> npm install -g mypackage

Now you have install package you just publish in the registry then write some code that access the installed package and access it’s methods. Create the main.js and write this code:

var math = require('mypackage');
console.log();
console.log('addition(2,14)'+ math.addition(2,14));
console.log();
console.log('addition(25,19)'+ math.subtraction(25,19));

The code requires the package and access it’s main file. You can run this by typing following in command prompt:

C:installedpackage> node main

Output

You will get this kind of output when you run the main file using command prompt:

C:installedpackage> node main
1 Call(s) are made!
addition(2,14)= 16
2 Call(s) are made!
subtraction(25,19)= 6

UnInstalling the package

You can also install the package from the local directory by just typing this command in command prompt window:

C:installedpackage> npm uninstall mypackage

To uninstall a global package:

C:installedpackage> npm uninstall -g mypackage

There you go !
That’s all from my side, must go for this create the little more complex applications and share with the community so it’ll help others to learn from you.

I will wait for your comments and suggestion, do suggest changes if you find any.
Thank You !

What do you think of this tutorial?
We want to hear from you! Please leave us a comment below and if you have any query please ask.
Experts are waiting for your queries ;) Cheers ! 
AsimNodeJS – Kickstart
Share this post

4 comments

Join the conversation
  • Usman Raza - February 18, 2016 reply

    Easy and nice tutorial

  • Tehseen - February 27, 2016 reply

    Great tutorial.

    Asim - February 27, 2016 reply

    Thank you please stay tuned for more posts

  • Noob - March 18, 2016 reply

    Waooo, Asim 🙂
    Can you teach me all that, its a nice article boi, you rocked 😉

Join the conversation