41
INTRODUCTION TO NODE.JS MANOJ CHAUHAN kalpcorporate [email protected] kalpcorporate.com Nodejs Developer

Kalp Corporate Node JS Perfect Guide

Embed Size (px)

Citation preview

INTRODUCTION TO NODE.JS

MANOJ CHAUHAN

[email protected]

kalpcorporate.com

Nodejs Developer

Overview What is node What is node.js Installation steps Create first Node application How it works ? Why node is so popular ? Where to use ? Advantages Disadvantages Statistics

What is Node

In a network, a node is a connection point, either a redistribution point or an end point for data transmissions.

A node is a point of intersection/connection within a network

What is Node.Js

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications.

A Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.

Node.js is an open-source, cross-platform runtime environment for developing server-side Web applications. Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript.

The runtime environment interprets JavaScript using Google's V8 JavaScript engine.

V8 is the JavaScript execution engine built for Google Chrome and 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.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient

How to install• Download: https://nodejs.org/en/download/

• Installation on UNIX/Linux/Mac OS X, and SunOSExtract the download archive into /usr/local, creating a NodeJs tree in /usr/local/nodejs.

• For example:• tar -C /usr/local -xzf node-v0.12.0-linux-x86.tar.gz• Add /usr/local/nodejs to the PATH environment variable.• export PATH=$PATH:/usr/local/nodejs

• Installation on Windows

• Use the MSI file and follow the prompts to install the Node.js. By default, the installer uses the Node.js distribution in C:\Program Files\nodejs.

• The installer should set the C:\Program Files\nodejs directory in window's PATH environment variable. Restart any open command prompts for the change to take effect.

Let’s start with First Application• Before creating actual Hello World ! application using

Node.js, let us see the parts of a Node.js application. A Node.js application consists of following three important parts :

• import required module: use require directive to load a javascript module

• create server: A server which will listen to client's request similar to Apache HTTP Server.

• read request and return response: server created in earlier step will read HTTP request made by client which can be a browser or console and return the response.

Creating Node.js Application

• Step 1: import required moduleuse require directive to load http module.

var http = require("http")

• Step 2: create an HTTP server using http.createServer method. Pass it a function with parameters request and response. Write the sample implementation to always return "Hello World". Pass a port 8081 to listen method.

http.createServer(function (request, response) {

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

// send the response body as "Hello World"

response.end('Hello World\n'); }).listen(8081);

// console will print the message console.log('Server running at http://127.0.0.1:8081/');

• Step 3: Save as a .js file eg. “test.js”and run : C:\Nodejs_WorkSpace>node test.js console message : “Server running at http://127.0.0.1:8081/”

Make a request to Node.js server

How it works

Both the REST API and the DB Query return the same queried response but the response differs in the format. Also, there is a big difference in the way you make requests.

For DB Query, you need to connect your app to the database, install appropriate drivers if required and even parse the response.

For a normal query, the response is the raw data. On the other hand, the REST API does not care about the app that is requesting the data.

A simple request can be can drafted and sent to the API just with the help of a simple old URL. The API parses it, queries the database on your behalf (which eliminates the need of drivers and sdks) and returns the structures response to you.

Why Node.JS is so popular ?• It is Non-blockingTo start using Node.JS, you must first understand the difference between Node.JS and traditional server-side scripting environment.

Other scripting languages uses separate server like Apache to run the application, which is the thread and process based, which means if the process is waiting for the I/O, whole thread is blocked.

Thread : In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system

Whereas Node.JS using the ‘HTTP’ module can run on a stand-alone web server.

It is asynchronous, event driven I/O. Every nodes instance runs in a single thread, so it can handle more number of concurrent requests as compared to Apache.

• It is FastFirst, Node is powered by Google’s V8 JavaScript Engine. The thing running you JavaScript code is the exact same thing the Chrome browser uses to run JavaScript code.

Now Question is why V8 JavaScript Engine?-It has unique speed compare to other JavaScript engines, it compiles JavaScript directly into native machine code, while other languages PHP & Ruby, Java all have to run through an interpreter every time when they are accessed.Node will run your code as though it’s native application.So it screams with speed.

Second, How fastly Node handles connections.

When 100 people connect at once, rather than having different threads, Node will loop over those connections and fire off any events your code should know about.

If a connection is new it will tell you .If a connection has sent you data, it will tell you .If the connection isn’t doing anything ,it will skip over it rather than taking up CPU time on it.

Everything in Node is based on responding to these events. So we can see the result, the CPU stay focused on that one process and doesn’t have a bunch of threads for attention. There is no buffering in Node.JS application it simply output the data in chunks.

It is Event-Driven“ Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient ”

Event driven programmingEvent driven programming is a programming in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs/threads.

Today, this concept is largely using in GUI Applications a mechanism is in place that listens for events and executes an action once the event occurs. This is the basic principle behind node.js!

The Event LoopThe event loop gives Node the capability to handle highly concurrent requests while still running “single-threaded”. In any event-driven application, there is generally a main loop that listens for events, and then triggers a callback function when one of those events is detected. Similarly, the event loop delegates I/O operations via POSIX interface while it still handles new requests and callbacks. Here is my take on how things work inside the node.js server:

The event loop simply iterate over the event queue which is basically a list of events and callbacks of completed operations. All I/O is performed asynchronously by the threads in the thread pool. Libuv component of Node.js plays a vital part in this.

If an item requires an I/O the event loop simple delegates the operation to the thread pool. Event loop continues execution of items in the event queue. Once the I/O operation is complete, the callback is queued for processing.. Event loop executes the callback and provide appropriate results. Since, it’s in a loop.. The process simply keeps going.

NPM The npm is the default package manager for the javascript runtime environment Node.js.

As of Node.js version 0.6.3, npm is bundled and installed automatically with the environment.

npm runs through the command line and manages dependencies for an application. It also allows users to install Node.js applications that are available on the npm registry.

npm is written entirely in JavaScript and was developed by Isaac Z.

• Built-in support for object databases    It is really common for Node.js applications to use object databases such as MongoDB. MongoDB, contrary to traditional SQL databases, it uses a document-based model instead of a relational model; this means that instead of tables, it uses objects resembling JSON.

• Wide support from IDEs and code editors   JavaScript has been around for a long time, so code hinting and highlighting is featured by a bunch IDEs like Visual Studio and Eclipse; also editors like Notepad++ and Sublime Text.

• Can be hosted almost anywhere    

Several web servers and cloud-based hosting providers support hosting of Node.js web applications out-of-the-box. To mention a couple: Google, Microsoft IIS, Heroku, Microsoft Azure, Amazon (AWS), and a bunch others.

• Debugger

• Node.js includes a full-featured out-of-process debugging utility accessible via a simple TCP-based protocol and built-in debugging client. To use it, start Node.js with the debug argument followed by the path to the script to debug; a prompt will be displayed indicating successful launch of the debugger:

• $ node debug myscript.js• < debugger listening on port 5858• connecting... ok

• Debugging Node.js in Chrome DevToolsnpm install -g devtool

Where to use ?Here’s just a sample of the many companies using Node in production or ramping up projects:

•  If you want to build streaming applications 

• If you plan to build CPU intensive applications (e.g. image processing) Then Node.js is not the perfect choice. You'll be able to get the job done, but other technologies may be a better fit.

AdvantagesOpen SourceNode.js is open source, so it’s free to use and no need to pay for license. There are also many open source modules supported by Node.js.

JavaScript as Programming LanguageIt uses JavaScript as a programming language for both front-end and back-end which increase programmer productivity and code reusability.

Scalable• You can scale your Node.js application by using two ways – Horizontal

Scaling and Vertical Scaling, which helps you to improve your application performance.

• In Horizontal scaling you can add more nodes to your existing system. In Vertical scaling you can add more resources to a single node.

Better PerformanceIt provides better performance, since Node.js I/O operations are non-blocking.

Also, it uses V8 JavaScript engine to execute JavaScript code. V8 engine compiles the JS code directly into machine code which make it fast.

Caching SupportNode.js supports caching of modules. Hence, when a Node.js modules is requested first time, it is cached into the application memory. So next calls for loading the same module may not cause the module code to be executed again.

Lightweight and Extensible

Node.js is based on JavaScript which can be executed on client side as well as server side. Also, it supports exchange of data using JSON which is easily consumed by JavaScript. This makes it light weight as compared to other frameworks.

REST API Support Using Node.js you can also develop RESTful services API easily.

Unit TestingIt supports unit testing out of box. You can use any JS unit testing frameworks like Mocha, Jasmin to test your Node.js code.

Server DevelopmentNode.js has some built-in API which help you to create different types of Server like HTTP Server, DNS Server, TCP Server etc.

Community SupportNode.js has a wide community of developers around the world. They are active in development of new modules or packages to support different types of applications development.

DisadvantagesIt doesn’t support multi-threaded programming.

It doesn’t support very high computational intensive tasks. When it executes long running task, it will queue all the incoming requests to wait for execution, since it follows JavaScript event loop which is single threaded.

Not good for executing synchronous and CPU intensive tasks.

Statistics

Our online IM Id’s for more convenientcommunication.

3, Suvarna Nagar Bungalow,Near St.Xaviers School Loyola,Ahmedabad-380013, Gujarat, India

+91 9879518121+91 757-294-0388(001) 415 251 KALP

kalpcorporatenihar.kalp

Thank You

[email protected]

[email protected]

[email protected]

kalpcorporate.com