Node JS


What is Node JS
Node js a platform which allows us to run JavaScript on a computer/server, we can do read, delete , update files and easily communicate with database.
How it works?
·        Computers doesn’t understand Javascript. 
·        Node js uses Chrome’s JavaScript V8 engine, it takes javascript, and  converts it into something it does understand – machine code.
Note:
·        Node.Js is written in C++
·        At the heart of node.js is the V8 engine.
·        The V8 engine converts our js into machine code.
 NodeJS with V8
Javascript ->(C++ Node js V8) -> Machine code

Features of Node.js

  • Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.
  • Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.
  • Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.
  • No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks.
Where to Use Node.js?
Following are the areas where Node.js is proving itself as a perfect technology partner.
·        I/O bound Applications
·        Data Streaming Applications
·        Data Intensive Real-time Applications (DIRT)
·        JSON APIs based Applications
·        Single Page Applications
Where Not to Use Node.js?
It is not advisable to use Node.js for CPU intensive applications.
Download:
You can download node JS from here: https://nodejs.org/en/download/
Version:
Check versions by running node -v in command line. 
Running:
If you want to run application, you need to go to application directory on command line then run node <Filename>
What is a Module in Node.js?
Consider modules to be the same as JavaScript libraries. A set of functions you want to include in your application
 To include a module, use the require() function with the name of the module:
Example: var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('Hello World!');
}).listen(8080);

Create Your Own Modules
You can create your own modules, and easily include them in your applications.
Example: myFile.js
 exports.myDateTime = function () {
    return Date();
};
To include myFile.js in app.js:
var dt = require('./myFile);
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write("The date and time are currently: " + dt.myDateTime());
    res.end();
}).listen(8080);

Node.js File System Module
The Node.js file system module allows you to work with the file system on your computer.
To include the File System module, use the require() method:
var fs = require('fs');
fs.readFile(<file path> , <format:utf8> , <function>) //Read file
Create/update Files: The File System module has methods for creating new files:
·        fs.append(<File file path> , <content> , <function>) // appends specified content to a file. If the file does not exist, the file will be created:
·        fs.open()  // method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created:
·        fs.writeFile() // method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:
Delete Files: To delete a file with the File System module,  use the fs.unlink() method.
fs.unlink('mynewfile2.txt', function (err) {
  if (err) throw err;
  console.log('File deleted!');
});
Create and remove directories:
fs.mkdir(<Path>,<callback func>) //to create directory 
fs.rmdir(<Path>) //to remove directory. Directory should empty before removing it.

Three important components in Node.JS
Import required modules − We use the require directive to load Node.js modules.
Create server − A server which will listen to client's requests similar to Apache HTTP Server.
Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.
Creating Node.js Application
Step 1 - Import Required Module
var http = require("http");
Step 2 - Create Server
We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 8081 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return "Hello World".
http.createServer(function (request, response) {
   response.writeHead(200, {'Content-Type': 'text/plain'});   
   response.end('Hello World\n');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081 port on the local machine.
Step 3 - Testing Request & Response
Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown below −
var http = require("http");
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});   
   response.end('Hello World\n');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
Now execute the main.js to start the server as follows −
$ node main.js
Verify the Output. Server has started.
Server running at http://127.0.0.1:8081/
Make a Request to the Node.js Server
Open http://127.0.0.1:8081/ in any browser and observe the following result.
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 the APIs of Node are written in such a way that they support callbacks.
For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the 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 a parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high number of requests without waiting for any function to return results.
Event Loop
Node.js is a single-threaded application, but it can support concurrency via the concept of event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they use async function calls to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute.
Node.js EventEmitter
Node.js allows us to create and handle custom events easily by using events module. Event module includes EventEmitter class which can be used to raise and handle custom events.
Example;
//get the reference of EventEmitter class of events module
var events = require('events');
//create an object of EventEmitter class by using above reference
var em = new events.EventEmitter();
//Subscribe for FirstEvent
em.on('FirstEvent', function (data) {
    console.log('First subscriber: ' + data);
});
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
What are Streams?
Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams −
  • Readable − Stream which is used for read operation.
    var readerStream = fs.createReadStream('input.txt' ,”utf8” ); // Create a readable stream
  • Writable − Stream which is used for write operation.   var writerStream = fs.createWriteStream('output.txt');
  • Duplex − Stream which can be used for both read and write operation.
  • Transform − A type of duplex stream where the output is computed based on input.
Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are −
·        data − This event is fired when there is data is available to read.
·        end − This event is fired when there is no more data to read.
·        error − This event is fired when there is any error receiving or writing data.
·        finish − This event is fired when all the data has been flushed to underlying system.
// Handle stream events --> data
readerStream.on('data', function(chunk) {
   data += chunk;
});
Piping the Streams
Piping is a mechanism where we provide the output of one stream as the input to another stream. It is normally used to get data from one stream and to pass the output of that stream to another stream. 
Example:
 var fs = require("fs");
var readerStream = fs.createReadStream('input.txt'); // Create a readable stream
var writerStream = fs.createWriteStream('output.txt'); // Create a writable stream
readerStream.pipe(writerStream); 
// Pipe the read and write operations // read input.txt and write data to output.txt
What is NPM?
NPM is a package manager for Node.js packages, or modules if you like.
www.npmjs.com hosts thousands of free packages to download and use.
The NPM program is installed on your computer when you install Node.js

What is a Package?
A package in Node.js contains all the files you need for a module.
Modules are JavaScript libraries you can include in your project.
How to install package?
In command line: npm install <Package name(ex: express)>
Package.json file:
Lists the packages that your project depends on and it allows you to specify the versions of a package that your project can use.
Express package:
Easy and flexible routing system
Integrating with many template engines.
Contains middleware framework




No comments:

Post a Comment