Light Version for web
NodeJS – Kickstart
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 especially for Node.js. But do not worry I am here now we will talk about the nitty-gritty of essential components of Node.js.

Getting started with Node.js

The backbone 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 applications that run across distributed devices need efficiency and a 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 into something (kidding). So without further ado let's 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 an HTTP request from Node.js you need a handler for that, so we need to include the http module. The HTTP module is a core built-in, low-level module that is highly optimized for performance. With the help of an 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 responds with the ‘Hello World’ and ‘Request Handled’ messages is sent to the console window. After when the createServer object is created it calls the listen to 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 assists the user to write on the console that the 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/
The request has been made from your browser to the newly created server (on the command prompt) you can see the response sent back from the server. The response will be written on the browser window and similarly, you can see the command prompt for log text which says :
Server Running !!
Request Handled
Yippee !! Congratulations, you have written your first Node.js website and successfully run it. You can refresh the browser window to send another request to the server and the server responds with the same string and will be displayed 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. The next example listens to the request that comes from the users and says 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 a URL module that provides help for parsing the QueryString. Url object has a parse method that accepts the actual URL, and the 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 received 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 the 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

Whenever you write code it’s best to reuse the code where possible. From a usability perspective in Node.js, we create modules. The module is a single entity that can hold some functionality and can be reused. In the previous examples, require functions were used to load modules, which provides code reuse when developing Node.js applications. So you can create a 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 within a function. At the very last line, the function is assigned to the start property of the exports object. Save the code in a ‘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 a relative path that’s why we use ‘ ./any_name.js ‘. The required function returns 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

The 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 the node package manager (npm) to publish your package or to install other packages. 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 a counter function that will call each time you will made any call. export property of module exports the function for the modules that wish 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 the 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 in the local module and present in the current folder of the package so is why we use this ./counter.js syntax. The reference is assigned 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 functions are exported with the help of an object. Like if there is a situation where you need to export two or more functions for the other modules to use, you just need to create the object for that. In this example addition represents the add function and subtraction represents the subtract function. The method name must not be the 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 two functions that we need to export by the package.

Creating the package.json file

Now it’s time to publish your package for 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 The node package manager is already installed when you install the Node.js for the 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 an account using the cmd node package manager. Type the following to add a 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 set up 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 locally for specific applications. Installing a package globally gives all the applications the 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 the 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 creates 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!