Monday, 28 May 2018

Understanding NodeJS With Simplified Way

Technology is evolving everyday and if you are not updated with it you can not survive in this highly competitive IT industry.

I still remember my first year of engineering when PHP is considered as god for web developers,But in just four years i have witnessed how rapid technologies evolves and now PHP has lot of competitors like Python(Django etc.), Ruby on Rails, NodeJS and many more.

Among all of them NodeJS is most popular and trending, NodeJS is not going to replace PHP, Rails or Python, but it has some awesome features that make it stands out of queue:

1. Uses complete Javascript for everything.
2. Very Fast as it is Based on Chrome V8 Engine .
3. Single Threaded and Non-Blocking Model.
4. At lower level it is written in C language so it its execution is very fast.


Actually what is NodeJS and why you should use it??


First of All NodeJS is not a programming language, It is just a Server Side Runtime Wrapper on Chrome V8 engine and uses Javascript as programming language, In past Javascript is considered as client side language which can be used to execute client side things like validations etc, but after the introduction of NodeJS Javascript can be used on Server side programing and you can make complete application with just using javascript. So it reduced the need of learning multiple languages for client and server programming. For building NodeJS Application we use various third party modules to implement different features, and NodeJS comes with its own popular package manager to manage different modules called NPM(Node Package Manager).

We have used the word Server a lot of time, its time to make our own server with NodeJS, that can accept requests  and return responses as we define.

To Get Started with Node JS first we need NodeJS Installed on our computer.

You Can download the LTS version of it from: https://nodejs.org/en/

Installation is quite straight forward.

As i said node uses a package manager to manage the dependency modules and all the application dependecy modules are mentioned in a file called "package.json",
So lets get started with some hands on actual implementation.

Step 1. Make a folder for you project suppose i name it "NodeJS_Starter".

Caution: Please don't be scared of black screen, you will love it.

Step 2. Open your favourite terminal(CMD,Powershell,gitBash etc),I am using gitbash, as shown in below screenshot.

Step 3. Now  write "npm init" in the terminal and it will ask some details about your application and create a "package.json" file containing all details and configuration of your project, as shown in the below screenshot. 
              

Step 4. Now you Have "package.json" file in root directory of your project.
Step 5. Now we have to Create the main Server file "index.js" which contains all the server stuffs.
Step 6: Here is the content of "index.js" for making a hello world server .
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

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(`Server running at http://${hostname}:${port}/`);
});

Explanation of Code:
Line 1: we have included http module which contains various http utilities, and assigned it to a variable called "http".
Line 2 & 3: We are assigning the value of  host address and port to variables on which we want to start the server.
Line 4: we are Creating the Server with our own configuration. every request has two parameters that is "req" and "res", in other words "req" is incoming pipe and "res" is outgoing pipe.
Line 5. We are setting the status code of  response to "200".
Line 6. We are setting the type of  response contained in the response.
Line 7. We are sending "Hello World" as body content.

Line 8 & 9. We are starting the server with above Configuration and port and logging a message to the console.

Step 6: To run and Test the server  open the terminal in the project directory and run "node index" command you will see the message "Server running at http://127.0.0.1:3000/" as shown in the below screenshot.


Step 7. Now Open "http://127.0.0.1:3000/" in your web browser and see the magic Happening. it will display "Hello World" in the browser , as shown in the screen shot below:

Congratulations, You have created your first nodejs server which responds with "Hello World".

In feature Posts i will come up with some more details request and response types and using third party modules and frameworks like ExpressJS.  

Sunday, 20 May 2018

how to run node.js on Android

I mainly use node.js since one year ago at work, and I really like it.
On my work project, I have to create a system which uses socket.io, but I don't have enough time to re-create a system using Android Java.
But I finally figure out how to run node.js on Android.

* This is really advanced topic, so I don't aim for Android beginners. Just for my memo.


1. Rooted your Android


First of all, you have to obtain root permission of your Android.
There are many ways and it's depends on your Android.
Ask to google.

2. Install Debian kit for Android


Debian kit for Android is really awesome tool.
You can install Debian onto your Android.
Download from Google Play store, then follow the instruction.

Debian kit for Android
https://play.google.com/store/apps/details?id=org.dyndns.sven_ola.debian_kit&hl=en

Instruction
http://sven-ola.dyndns.org/repo/debian-kit-en.html

$> cd /data/local/tmp
$> wget http://sven-ola.dyndns.org/repo/debian-kit-1-5.shar
$> sh debian-*
...
... (after the set up)
...
$> deb  // start debian
#> apt-get update
#> apt-get upgrade
#> apt-get install andromize
#> apt-get install sudo
...
... (install another packages if you want)
...

3. Install node.js


Before install node.js, you also need couple of debain packages.
#> apt-get install openssl build-essential python libssl-dev git-core
To install node.js for Debian, you might need to compile node.js from source code. 
#> cd /data/local/tmp
#> wget http://nodejs.org/dist/node-latest.tar.gz
#> tar zxf node-latest.tar.gz
#> cd node*
#> ./configure
#> make
#> make install

If your Android uses ARM architecture, you might be get couple of errors.
To prevent these, add couple of parameters.
#> ./configure --without-snapshot --dest-cpu=arm --dest-os=linux

Snapshot is a technology to run node.js quickly on V8 engine.
But there are bugs for ARM architecture, so you should disable snapshot.
http://stackoverflow.com/questions/16628118/node-js-source-code-build-giving-segmentation-fault-on-arm#16789296

Also you might face an error with "For thumb inter-working we require an architecture which supports blx".
Then get rid of the error code in the macro.
It doesn't affect (at least for me)

HOW TO INSTALL NODE.JS 0.8 ON ARM BASED SBC FOX BOARD G20 > 
STEP 8: CUSTOMIZE MACRO-ASSEMBLER-ARM.CC
http://www.yoovant.com/how-install-node-js-0-8-arm-based-sbc-fox-board-g20/

Congratulation!

Now node.js should run on your Android.

#> node -e "console.log('Hello Node.js on Android')"

Friday, 18 May 2018

Node.js 10.0.0 is Available Now!

The Node.js project has recently released its latest version Node.js 10.0.0 on 24th April. It is the seventh major Node.js release since the launch of the Node.js Foundation. It is going to be the next Active Long Term Support(LTS) branch in October of 2018. So, it will be supported for next three years. Some of its key improvements include adding support for the OpenSSL 1.1.0 security toolkit. However, it focuses mainly on incremental improvements.
Being a point update, this version arrives with full support for N-API, LTS status to come, and more unique features.
In this blog, you will find some of the key updates of iOS 11.0.3 in details along with some major updates on its previous versions.
Click here to download its latest version.

While Node.js 10.0.0 ships with NPM 5.7, the 10.x line will be upgraded to NPM Version 6 later on; NPM 6 will offer performance, stability, and security improvements. In addition to its security support, some other features in the Node.js 10.0.0 release include the following:


1) With the adoption of error codes, there are error-handling improvements in order to ease constant error-checking.
2) N-API (API Node.js), which moves from a beta version to a stable one, and provides a stable module API independent of the changes in the V8 JavaScript engine underlying Node.js. The API helps the module maintainers and production implementations, facilitating updates.
3) Performance boosts via V8, including for the async generator and array.
4) An API in version 10.0.0 allows user code to enable and disable trace events on demand at runtime, for greater flexibility in diagnosing problems in applications.
5) Increased visibility into code performance issues via trace events, with the 10.0.0 release.
6) Improvements in the JavaScript language, including the prototype.toString (), which now returns exact segments of the source code text and mitigations for side channel vulnerabilities to prevent information leaks.

Read this: Top 10 Advantages of Using NodeJS


However, there are more features to come in the later versions of the Node.js 10.0.0. Some of these features are listed below:


– Better ECMAScript module support (ES) 6. Node.js has had its own module system, but ECMAScript 6 offers a standardized module system. The plan is to provide an ECMAScript 6 implementation compatible with the browser that coexists with the existing Node.js modules.
– HTTP/2, a higher-performing successor to HTTP.

Checkout the following Node.js 10.0.0 changelog:


Source: GitHub
Check out the complete Node.js 10 changelog and its new additions by clicking here.

Other efforts in the Node.js project, which are not directly related to the Node.js 10 or Node.js 11 launch lines, include:


–  Continued progress in security triage for third-party NPM modules.
– Functional tests for third-party modules, to ensure that dependencies are maintained.

The following characteristics are expected to reach Node.js 11.x:


– Better diagnostic capabilities, which is becoming a more important area since Node.js is increasingly used in production applications.
– The use of JavaScript promises in the core of Node.js provides a better adaptation for developers who want to use API type promise.
– Support for more construction/automation infrastructure, with additional support for tools and scripts. Support will be added for newer operating systems, while older operating systems would be discarded.

Thursday, 10 May 2018

Node.js : Making HTML template using EJS and Layouts

I have used Node.js for multiple applications and prototypes I have to build, and I always wanted to find a very simple application template that would provide a simple starting point when creating new applications. As I could not find something simple and light weighted, I decided to create a simple application template and will now share it with you all. 

For this post, I'll assume you know how to create your initial project either using Node.js Express or in my case, using WebStorm

1) Create initial express project using EJS as template engine 

2) Download Twitter Bootstrap and place it in public/lib/bootstrap 

3) Download jQuery and place it in public/lib/jquery 

4) Add local-ejs in order to get support for layouts and hinheritance 

Install ejs-locals
1npm install ejs-locals --save
Use ejs-locals as your app engine in app.js
1var express = require('express');
2var engine = require('ejs-locals');
3...
4
5app.engine('ejs', engine);
6app.set('view engine''ejs');
5) Create the basic template 

The layout.ejs is where the basic page layout is defined. It's composed of three main parts : head.ejs, header.ejs and the footer.ejs; and also provides a place for you to add your own content: body.
01<!DOCTYPE html>
02<html lang="en">
03<head>
04    <% include templates/head.ejs%>
05</head>
06
07<body>
08
09<% include templates/header.ejs%>
10
11
12<!-- Insert Body here -->
13<div class="container">
14
15    <div class="starter-template">
16        <%- body %>
17    </div>
18
19</div><!-- /.container -->
20
21<% include templates/footer.ejs%>
22
23</body>
24</html>
When we look into the head.ejs, we see mainly some meta information and the inclusion of CSS and JavaScript libraries. 

01<title><%= title %></title>
02<meta name="viewport" content="width=device-width, initial-scale=1.0">
03<meta name="description" content="nodeJS Template">
04<meta name="author" content="Luciano Resende">
05
06<!-- styles -->
07<link href="/lib/boostrap/css/bootstrap.css"rel="stylesheet">
08<link href="/stylesheets/style.css" rel="stylesheet">
09
10...
The header.ejs is where the top navigation bar, where the application title, and menu entries are defined:
01<div class="navbar navbar-inverse navbar-fixed-top">
02    <div class="container">
03        <div class="navbar-header">
04            <button type="button" data-toggle="collapse"data-target=".navbar-collapse" class="navbar-toggle"><span
05                        class="icon-bar"></span><spanclass="icon-bar"></span><span class="icon-bar"></span></button>
06            <a href="#" class="navbar-brand">Application</a></div>
07        <div class="collapse navbar-collapse">
08            <ul class="nav navbar-nav">
09                <li class="active"><a href="/">Home</a></li>
10                <li><a href="/users">Users</a></li>
11            </ul>
12        </div>
13    </div>
14</div>
And the footer.ejs defines copyright information or any other information that you want present on every page footer:
1<div class="footer">
2    <div class="container">
3        <p class="text-center text-muted">© Copyright Luciano Resende - 2014</p>
4    </div>
5</div>
Now, to build your pages, you would include the layout on the top of the page, and start building your content like the sample below.
1<% layout('layout') -%>
2
3<h1>Bootstrap starter template</h1>
4<p class="lead">Page content goes here.</p>
Now you can run your app using :
1node bin/www
And the ui looks just like the sample Twitter Bootstrap sample page
Hopefully this can help you get started with new applications more quickly. 

The code is also available in this github repository : node-app-template