Node.js Tutorial
Wednesday, February 13, 2019
Wednesday, July 22, 2015
Amazing facts about NodeDotJs
Node.js is a runtime system that makes it easy to build a network or other event-driven application servers. Here are the six things you need to know about it:
1. JSON has won
JSON (JavaScript Object Notation) is a practical, compound, wildly popular data exchange format. JSON has enabled JavaScript developers to quickly construct APIs and foster interoperability at scale -- a key objective for Node.js coders. JSON's stark simplicity can be expressed in just five railroad parse diagrams, notably without the self-conscious preening of XML and its scheming friends (SOAP, XSD, WS-*, RELAX-NG, and their endless committee meetings).
JSON and JavaScript have reinforced each other's importance. Back in the early days of the Web, dynamic data in the browser had to be manipulated, filtered, and operated on by the only reasonably comprehensible non-plugin language available: JavaScript. Regardless of its original network-presentable format, data needed to be marshalled into a JavaScript object. The dependence on JSON for general purpose data description gave rise to document-oriented NoSQL databases such as MongoDB and CouchDB. It's all JSON all the time today.
2. JavaScript is everywhere
JavaScript is a quirky, object-oriented, C-like language. It's the only choice for developing applications in the browser, with a new framework introduced every week to woo developers. And with Node.js, JavaScript has spilled over to the server. Competing implementation teams have driven JavaScript interpreters forward, so that Google's V8 engine is respectably fast -- fast enough to reside at the core of Node.js.
JavaScript also has the internal capability to handle the event loop mechanism in a straightforward way. Other languages have this capability, which are used by their own evented systems. Python has Twisted and Ruby has EventMachine. But because of history, both of those event-loop systems come freighted with relatively easy ways to make a particular kind of performance mistake, while JavaScript remains relatively free of this peril.
JavaScript also runs across many OS environments, having historically had to support them in the browser. This, along with the libuv library to help abstract away some of the operating system differences, means that Node.js has a broad footprint.
But the biggest force for JavaScript's migration to the server side is human. Programmers have to do less mental context-switching between a Web browser and the server. There are even efforts to unify the environments between client and the server so that code can run equally well in either location, further simplifying the model and leading to increased productivity.
3. Sharing is encouraged
The ethos of the Node.js community is "share gleefully." It's frighteningly easy to share packages of library code -- technically, culturally, procedurally, and legally. The Node Package Manager is included with Node.js and has grown to a repository of nearly 50,000 packages, making it likely that another developer has already packaged up a solution to your problem, or even some less common ones.
Node.js' namespace philosophy is essentially the absence of one, letting any author publish under an unused module name in the shared public repository. Sharing code under the MIT open source license is highly recommended in the community, which also makes cross-pollination of code relatively worry-free (and lawyer-free) from an intellectual property perspective. Finally, the community is highly engaged in binding interesting C libraries like computer vision (OpenCV) and the Tesseract open source optical character library. The latter, for example, makes possible weekend projects like Imdex that process images from the Web so they can be automatically searched for written content.
4. Node Package Manager works broadly
Speaking of managing library dependencies, the Node Package Manager deserves to be called out. Node Package Manager is the root of almost all deployment systems for Node.js and underlies the many PaaS (platform-as-a-service) providers for Node.js, actually making it somewhat easy to move smaller applications between providers. Its simple, dependable package management has let the Node ecosystem grow extremely well in recent history, to the point that the underlying public service now needs to scale to the next level.
5. 'Batteries not included' minimalism
Node.js applications and Node.js Core itself are broken down into small modules that are composed and shared. Each package and tool can be scoped tightly and crafted to be manageable. These can then be baked together -- often without too much unnecessary kneading. The low-barrier, carefree nature of creating a module also encourages experimentation in the community, and there's quite a bit of overlap and experimentation in the package population. When executed well, each package typically handles one task (e.g. node-optimist.js: 'light-weight [command-line] option parsing').
6. Instrumentation
Finally, Node.js is well instrumented for production usage. What that means is that there are the tools to help bring an application to full production readiness and performance. As with any maturing technology, there are areas where more documentation, tools, and best practices could be helpful. But as Node.js heads towards its next major release, it's on fairly solid footing.
7. JavaScript on the server? What is this witchcraft?
For those of you geeks who don’t live in caves, skip to the next section. For every one else (noobs, I’m talking to you too), keep reading.
Okay, you know how server-side code is usually written in PHP, or Python, or (sigh) .NET? And browser-side code is usually written in JavaScript? Well, as it turns out, JavaScript is pretty awesome, and getting awesomer by the day. So some clever chap thought that it might be cool to write server-side code in JavaScript too, and that’s how server-side JavaScript was born.
It also turns out that the current standard JavaScript interpreter V8 (by Google, thank the Lord for them) is blazing fast, and makes JavaScript on the server around three times faster than Python 3 and around ten times faster than PHP.
But the real awesome thing about JavaScript on the server is that you can use the same code that you use in the browser (for example, form validation) in your server too. And, with a standard language like JavaScript being used in every level on the web, more libraries and plugins are being made every day so you don’t have to make your own session management system, or static file server, or user access system. You can get a solid web app ready to be deployed in half the time, and have more time for your kids, or friends, or WoW addiction, or whatever.
8. Coyote meets Roadrunner
Okay, let’s talk speed. How fast is Node compared to the alternatives?
From the creator’s presentation,
100 concurrent clients 1 megabyte responsenode 822 req/sec nginx 708 thin 85 mongrel 4
(more is better)Seeing as nginx is the current heart-throb of the web developer’s server platforms (if you haven’t heard of it, just know that it blows Apache out of the water), Node claims high score by beating it.
Tuesday, May 26, 2015
20 Best Node.js Frameworks for Developers 2015
Node.js frameworks can help you develop web applications more user-friendly. And with lot of features and functionality to develop huge web applications. These 20 best Node.js frameworks 2015 helps to speed up your web applications development.
Node.js is a JavaScript platform that allows you to build large scale
web applications. Node.js frameworks a platform to build scalabe
applications by using Javascript as its scripting
language. Node.js frameworks are super useful when it comes to web
applications development and also it speed up your development
process. In this article we have collected list of 20 Best Node.js
Frameworks which will help you to develop web applications faster. We
hope you’ll find our best Node.js frameworks useful and please comment
below if you have or know any fresh & useful Node.js frameworks.
Best Node.js frameworks 2015
Express
Total
FREE SERVER FRAMEWORK FOR BUILDING WEB SITES AND WEB APPLICATIONS USING JAVASCRIPT, HTML AND CSS.
SocketStream
SocketStream is a framework for Realtime Web Apps
Socket.IO enables real-time bidirectional event-based communication.
It works on every platform, browser or device, focusing equally on reliability and speed.
It works on every platform, browser or device, focusing equally on reliability and speed.
KISS
Object-oriented web framework on Node.js, written in CoffeeScript.
METEOR
Meteor is an open-source platform for building top-quality web apps in a
fraction of the time, whether you’re an expert developer or just
getting started.
MEAN
MEAN is an opinionated fullstack javascript node.js framework – which simplifies and accelerates web application development.
SPINE
Spine.app is a Spine application generator. It'll create the basic
application structure, as well as controllers and models. This can then
be served up, or compiled, using HEM.
+
KOA
Koa next generation node.js framworks for web
WINTERSMITH
Flexible, minimalistic, multi-platform static site generator built on top of node.js.
FLATIRON
Flatiron is an adaptable framework for building modern web applications.
It was built from the ground up for use with Javascript and Node.js.
COKE
COKE is a lightweight node.js MVC framework that speeds up your web
development. It’s simple, it’s modularized, it’s somking fast!
SLEEK
One step solution for faster, flexible and user friendly web apps.
LOCOMOTIVE
Locomotive is a web node.js frameworks. Locomotive supports MVC
patterns, RESTful routes, and convention over configuration, while
integrating seamlessly with any database and template engine.
TOWER
Small components for building apps, manipulating data, and automating a distributed infrastructure.
GEDDY
A simple, structured node.js frameworks. The original MVC Web framework
for Node a simple structured way to create full stack javascript
applications.png
PARTIAL
Free web application framework for building Web sites and Web
applications using JavaScript, HTML and CSS. From web developer for web
developers.
KRAKEN
Kraken is a secure and scalable layer that extends express by providing
structure and convention. Though kraken is the main pillar of our
framework, the following modules can also be used independently:
DERBY
Expect more from your MVC. DerbyJS is a full-stack framework for writing modern web applications.
STAPES
Stapes.js is designed to be agnostic about your setup and style of coding.
Tuesday, May 12, 2015
Node.js - Event Loop
Node js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed.
Event Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, delcares functions and then simply waits for event to occur.In an 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.
While Events seems similar to what callbacks are. The difference lies in the fact that callback functions are called when an asynchronous function returns its result where as event handling works on the observer pattern. The functions which listens to events acts as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events and event listeners as follows:
// Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter();
Following is the syntax to bind event handler with an event:
// Bind event and even handler as follows eventEmitter.on('eventName', eventHandler);
We can fire an event programatically as follows:
// Fire an event eventEmitter.emit('eventName');
Example
Create a js file named main.js having the following code:// Import events module var events = require('events'); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); // Create an event handler as follows var connectHandler = function connected() { console.log('connection succesful.'); // Fire the data_received event eventEmitter.emit('data_received'); } // Bind the connection event with the handler eventEmitter.on('connection', connectHandler); // Bind the data_received event with the anonymous function eventEmitter.on('data_received', function(){ console.log('data received succesfully.'); }); // Fire the connection event eventEmitter.emit('connection'); console.log("Program Ended.");
Now let's try to run the above program as check the output:
$ node main.js
This will produce following result:
connection succesful. data received succesfully. Program Ended.
How Node Applications Work?
In Node Application, any async function accepts a callback as a last parameter and the callback function accepts error as a first parameter. Let's revisit the previous example again. Create a text file named input.txt having following contentThis Blog is provide self learning technique to learn the things in simple and efficience way.
Create a js file named main.js having the following code:
var fs = require("fs"); fs.readFile('input.txt', function (err, data) { if (err){ console.log(err.stack); return; } console.log(data.toString()); }); console.log("Program Ended");
Here fs.readFile() is a async function whose purpose is to read a file.
If an error occurs during read of file, then err object will contain the
corresponding error else data will contain the contents of the file.
readFile passes err and data to callback function after file read
operation is complete, which finally prints the content.
Programe Ended
This Blog is provide self learning technique to learn the things in simple and efficience way.
Node.js - Callbacks Concept
What is Callback?
Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks.For example, a function to read a file may start reading file and return the control to execution environment immidiately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.
Blocking Code Example
Create a text file named input.txt having following contentThis Blog is provide self learning technique to learn the things in simple and efficience way.
Create a js file named main.js which has the following code:
var fs = require("fs"); var data = fs.readFileSync('input.txt'); console.log(data.toString()); console.log("Program Ended");
Now run the main.js to see the result:
$ node main.js
Verify the Output
This Blog is provide self learning technique to learn the things in simple and efficience way.
Program Ended
Non-Blocking Code Example
Create a text file named input.txt having following content
This Blog is provide self learning technique to learn the things in simple and efficience way.
Update main.js file to have following code:
var fs = require("fs"); fs.readFile('input.txt', function (err, data) { if (err) return console.error(err); console.log(data.toString()); }); console.log("Program Ended");
Now run the main.js to see the result:
$ node main.js
Verify the Output
Program Ended
This Blog is provide self learning technique to learn the things in simple and efficience way.
These two examples explain the concept of blocking and non-blocking
calls. First example shows that program blocks until it reads the file
and then only it proceeds to end the program where as in second example,
program does not wait for file reading but it just proceeded to print
"Program Ended" and same time program without blocking continues reading
the file.Thus, a blocking program executes very much in sequence and from programming point of view its easier to implement the logic but non-blocking programs does not execute in sequence, so in case a program needs to use any data to be processed, it should be kept with-in the same block to make it sequential execution.
You can start from here for More..
Monday, May 11, 2015
Node.js - npm (Node Package Manager)
Node Package Manager (npm) provides following two main functionalities:
- Online repositories for node.js packages/modules which are searchable on search.nodejs.org
- Command line utility to install Node.js packages, do version management and dependency management of Node.js packages.
$ npm --version 2.7.1
If you are running old version of npm then its damn easy to update it to the latest version. Just use the following command from root:
$ sudo npm install npm -g /usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js npm@2.7.1 /usr/lib/node_modules/npm
Installing Modules using npm
There is a simple syntax to install any Node.js module:$ npm install <Module Name>
For example,
following is the command to install a famous Node.js web framework module called express:
$ npm install express
Now you can use this module in your js file as following:
var express = require('express')
Global vs Local installation
By default, npm installs any dependency in the local mode. Here local mode refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require() method. For example when we installed express module, it created node_modules directory in the current directory where it installed express module.$ ls -l total 0 drwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules
Alternatively you can use npm ls command to list down all the locally installed modules.
Globally installed packages/dependencies are stored in system directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. Now Let's try installing express module using global installation.
$ npm install express -g
This will produce similar result but module will be installed globally. Here first line tells about the module version and its location where it is getting installed.
express@4.12.2 /usr/lib/node_modules/express ├── merge-descriptors@1.0.0 ├── utils-merge@1.0.0 ├── cookie-signature@1.0.6 ├── methods@1.1.1 ├── fresh@0.2.4 ├── cookie@0.1.2 ├── escape-html@1.0.1 ├── range-parser@1.0.2 ├── content-type@1.0.1 ├── finalhandler@0.3.3 ├── vary@1.0.0 ├── parseurl@1.3.0 ├── content-disposition@0.5.0 ├── path-to-regexp@0.1.3 ├── depd@1.0.0 ├── qs@2.3.3 ├── on-finished@2.2.0 (ee-first@1.1.0) ├── etag@1.5.1 (crc@3.2.1) ├── debug@2.1.3 (ms@0.7.0) ├── proxy-addr@1.0.7 (forwarded@0.1.0, ipaddr.js@0.1.9) ├── send@0.12.1 (destroy@1.0.3, ms@0.7.0, mime@1.3.4) ├── serve-static@1.9.2 (send@0.12.2) ├── accepts@1.2.5 (negotiator@0.5.1, mime-types@2.0.10) └── type-is@1.6.1 (media-typer@0.3.0, mime-types@2.0.10)
You can use following command to check all the modules installed globally:
$ npm ls -g
Using package.json
package.json is present in the root directory of any Node application/module and is used to define the properties of a package. Let's open package.json of express package present in node_modules/express/{ "name": "express", "description": "Fast, unopinionated, minimalist web framework", "version": "4.11.2", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, "contributors": [ { "name": "Aaron Heckmann", "email": "aaron.heckmann+github@gmail.com" }, { "name": "Ciaran Jessup", "email": "ciaranj@gmail.com" }, { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" }, { "name": "Guillermo Rauch", "email": "rauchg@gmail.com" }, { "name": "Jonathan Ong", "email": "me@jongleberry.com" }, { "name": "Roman Shtylman", "email": "shtylman+expressjs@gmail.com" }, { "name": "Young Jae Sim", "email": "hanul@hanul.me" } ], "license": "MIT", "repository": { "type": "git", "url": "https://github.com/strongloop/express" }, "homepage": "http://expressjs.com/", "keywords": [ "express", "framework", "sinatra", "web", "rest", "restful", "router", "app", "api" ], "dependencies": { "accepts": "~1.2.3", "content-disposition": "0.5.0", "cookie-signature": "1.0.5", "debug": "~2.1.1", "depd": "~1.0.0", "escape-html": "1.0.1", "etag": "~1.5.1", "finalhandler": "0.3.3", "fresh": "0.2.4", "media-typer": "0.3.0", "methods": "~1.1.1", "on-finished": "~2.2.0", "parseurl": "~1.3.0", "path-to-regexp": "0.1.3", "proxy-addr": "~1.0.6", "qs": "2.3.3", "range-parser": "~1.0.2", "send": "0.11.1", "serve-static": "~1.8.1", "type-is": "~1.5.6", "vary": "~1.0.0", "cookie": "0.1.2", "merge-descriptors": "0.0.2", "utils-merge": "1.0.0" }, "devDependencies": { "after": "0.8.1", "ejs": "2.1.4", "istanbul": "0.3.5", "marked": "0.3.3", "mocha": "~2.1.0", "should": "~4.6.2", "supertest": "~0.15.0", "hjs": "~0.0.6", "body-parser": "~1.11.0", "connect-redis": "~2.2.0", "cookie-parser": "~1.3.3", "express-session": "~1.10.2", "jade": "~1.9.1", "method-override": "~2.3.1", "morgan": "~1.5.1", "multiparty": "~4.1.1", "vhost": "~3.0.0" }, "engines": { "node": ">= 0.10.0" }, "files": [ "LICENSE", "History.md", "Readme.md", "index.js", "lib/" ], "scripts": { "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/" }, "gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada", "bugs": { "url": "https://github.com/strongloop/express/issues" }, "_id": "express@4.11.2", "_shasum": "8df3d5a9ac848585f00a0777601823faecd3b148", "_from": "express@*", "_npmVersion": "1.4.28", "_npmUser": { "name": "dougwilson", "email": "doug@somethingdoug.com" }, "maintainers": [ { "name": "tjholowaychuk", "email": "tj@vision-media.ca" }, { "name": "jongleberry", "email": "jonathanrichardong@gmail.com" }, { "name": "shtylman", "email": "shtylman@gmail.com" }, { "name": "dougwilson", "email": "doug@somethingdoug.com" }, { "name": "aredridel", "email": "aredridel@nbtsc.org" }, { "name": "strongloop", "email": "callback@strongloop.com" }, { "name": "rfeng", "email": "enjoyjava@gmail.com" } ], "dist": { "shasum": "8df3d5a9ac848585f00a0777601823faecd3b148", "tarball": "http://registry.npmjs.org/express/-/express-4.11.2.tgz" }, "directories": {}, "_resolved": "https://registry.npmjs.org/express/-/express-4.11.2.tgz", "readme": "ERROR: No README data found!" }
Uninstalling a module
Use following command to uninstall a Node.js module.$ npm uninstall express
Once npm uninstall the package, you can verify by looking at the content of /node_modules/ directory or type the following command:
$ npm ls
Updating a module
Update package.json and change the version of the dependency which to be updated and run the following command.$ npm update express
Search a module
Search package name using npm.$ npm search express
Create a module
Creation of module requires package.json to be generated. Let's generate package.json using npm, which will generate basic skeleton of the package.json.$ npm init
This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sane defaults. See 'npm help json' for definitive documentation on these fields and exactly what they do. Use 'npm install <pkg> --save' afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. name: (webmaster)
You will need to provide all the required information about your module.
YOu can take help from the above mentioned package.json file to
understand the meanings of various information demanded. Once
package.json is generated. Use the following command to register
yourself with npm repository site using a valid email address.
$ npm adduser Username: nodeuser Password: Email: (this IS public) nodeuser@gmail.com
Now its time to publish your module:
$ npm publish
If everything is fine with your module, then it will be published in the reporsitory and will be accessible to install using npm like any other other Node.js module.
Subscribe to:
Posts (Atom)