Thursday, 9 March 2017

Node js Tutorial for beginners with example - Page 2

Node js Tutorial for beginners with examples - page 2

Question: Does nodeJS support concurrency?
Yes, It support concurrency where as it is single thread application.
It uses event and callbacks to support concurrency.
Node uses observer pattern and thread keeps an event loop and whenever a task gets completed.


Question: What is event driven programming?
Event driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions, sensor outputs, messages from other programs/threads.


Question: How NodeJS starts?
When Node starts its server, it simply initiates all variables, declares functions and then simply waits for the event to occur.


Question: How node use Event-Driven programming?
In an event-driven application, there is a main loop that listens for events, and then triggers a callback function when one of those events is detected.
The functions that listen to events act as Observers, whenever an event gets fired, listener function starts executing.
Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners.


Question: How to read content from text file?
In Node "async function" accepts a callback as the last parameter and a callback function accepts an error as the first parameter.
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
   if (err){
      console.log(err.stack);
      return;
   }
   console.log(data.toString());
});



Question: What is EventEmitter class?
All objects that emit events are instances of the EventEmitter class.
eventEmitter.on() function that allows one or more functions to be attached.
When the EventEmitter emits an event, all functions attached to that event are called synchronously.


Question: Give an exmaple of EventEmitter?
const EventEmitter = require('events');
var eventEmitter = new events.EventEmitter();

//call when emit
eventEmitter.on('event', function(a, b) {
  console.log(a, b, this);  
});
//Email the data
eventEmitter.emit('event', 'a', 'b');



Question: What are common EventEmitter methods?
  1. addListener(event, listener): Add one or more listener to the event.
  2. on(event, listener): Adds a listener at the end of the listeners array for the specified event.
  3. once(event, listener): Adds a one time listener to the event.
  4. removeListener(event, listener): Removes a listener from the listener array for the specified event



Question: How to create buffer in node?
Node provides Buffer class which store raw data similar to an array of integers/string but corresponds to a raw memory allocation.
//Create a buffer
var buf = new Buffer([107, 207, 370, 470, 570]);

//Convert Buffer to JSON
buf.toJSON()

//Print the buffer
console.log(buf.toJSON());

//Concatinate to buffer
var buf1 = new Buffer('Quick Learnig');
var buf2 = Buffer.concat([buf,buf1]);

//Copy buffer
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])

//Slice Buffer
buf.slice([start][, end])

//Buffer Length
buf.length;



Question: What are Streams in NodeJS?
Streams are objects that let you read data from a source OR write data to a destination.


Question: What are different type of Streams?
  1. Readable: used for read.
  2. Writable: used for write.
  3. Duplex: used for read and write.
  4. Transform: type of duplex stream where the output is computed based on input
Each type of Stream(Readable,Writable,Duplex,Transform) is an EventEmitter instance.


Question: What type of events are through by streams(Readable,Writable,Duplex,Transform) ?
data
end
error
finish


Question: Give an example of working streams in NodeJS?
var fs = require("fs");
var textdata = '';
var readerStream = fs.createReadStream('test/inputdata.txt');
// Set the encoding to be utf8. 
readerStream.setEncoding('UTF8');

readerStream.on('data', function(chunk) {
    textdata += chunk;
});
readerStream.on('end', function() {
    console.log('All data are:'+textdata);
});
readerStream.on('error', function(err) {
    console.log(err.stack);
});

console.log("Program finished.");



Question: What is Piping the Streams?
Piping is a mechanism where we provide the output of one stream as the input to another stream.
means get output data from one stream and to pass to another stream.


Question: What is Chaining the Streams?
Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations.


Question: Give an example of Synchronous and Asynchronous?
Synchronous: In Synchronous, all request execute one by one means it blocks a program during its execution. see example
var fs = require("fs");
// Synchronous reading
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());


Asynchronous: In Asynchronous, one request does not wait for the execution of another request. Basically its good programming. Asynchronous methods take two parameter first is error and second one is data. See example:
var fs = require("fs");
// Asynchronous reading
fs.readFile('input.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});



Question: How to open file in read mode? What are different flags available?
var fs = require("fs");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
  console.log("File opened successfully!");     
});


r Open file for reading. An exception occurs if the file does not exist.
r+ Open file for reading and writing. An exception occurs if the file does not exist.
rs Open file for reading in synchronous mode.
rs+ Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with caution.
w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like 'w' but fails if the path exists.
w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like 'w+' but fails if path exists.
a Open file for appending. The file is created if it does not exist.
ax Like 'a' but fails if the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like 'a+' but fails if the the path exists.


Question: How to get current filename OR dirname?
Get Filename
__filename

Get dirname
__dirname



Friday, 3 March 2017

Node js tutorial for beginners with examples

node js tutorial for beginners with examples

Question: What is REPL?
It represents a computer environment like a Unix/Linux shell where a command is entered and the system responds with an output.


Question: What is full form of REPL?
Read. Eval. Print. Loop.


Question: How to start REPL?
Type following command and press enter key.
node



Question: How to calculate 2+2 in Node REPL?
Just type 2+2 and press enter key in REPL Mode.


Question: How to see previous result in REPL?
Use Underscore to see the previous results.
_



Question: What we can do in REPL?
  1. Simple Expression
  2. Use Variables
  3. Multiline Expression
  4. Underscore Variable



Question: What are most common REPL Commands?
ctrl + c ? terminate the current command.
ctrl + c twice ? terminate the Node REPL.
ctrl + d ? terminate the REPL.
Up/Down Keys ? see command history.
tab Keys ? list of current commands.
.help ? list of all commands.
.break ? exit from multiline expression.
.clear ? exit from multiline expression.
.save filename ? save the current session to a file.
.load filename ? load file content in Node REPL session.


Question: What is the difference between local and global module in Node.js?
When we Installed a module locally, then we need to use require() to use module.
When we Installed a module globally, then we need't to use require() to use module.


Question: When to use local and global module?
If we are going to run it on the command line, then we must install the module globally.


Question: How to install mysql locally?
npm install mysql



Question: How to install mysql globally?
npm install mysql -g



Question: What is package.json in module?
All npm packages contain a file, usually in the project root, called package.json.
package.json file holds various metadata relevant to the project.
This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies.
It can also contain other metadata like description, version, license and configuration data.


Question: Give the sample of package.json?
{
  "name" : "name of project",
  "description" : "Project description.",
  "homepage" : "http://example.com",
  "keywords" : ["keyword1", "keyword2", "keyword3", "keyword4", "keyword5"],
  "author" : "hellouser ",
  "contributors" : [],
  "dependencies" : [],
  "repository" : {"type": "git", "url": "git://github.com/example/example.git"},
  "main" : "project.js",
  "version" : "1.2.7"
}


Question: Does package.json exist for each module?
Yes, each package contain the package.json.
It exist in root of module.


Question: Does package.json exist for each module?
Yes,
Each module have its own package.json


Question: How to search a new module?
npm search mysql



Question: How to update existing module?
npm update mysql



Question: Can we create a new module and published?
Yes, We can create a new module.
Following are different ways.
  1. Create package.json
  2. Create a new module using "npm init" commond.
  3. Add the user for new module.
  4. Publish the node module using "npm publish"



Question: Give example Blocking vs non-blocking in node.js?
Create a file with "input.txt" with content "Hello I am here.";


Blocking code
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("End of script");

Output
Hello I am here.
End of script

Non-Blocking code
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
});
console.log("End of script");
Output
End of script
Hello I am here.


Question: How to install express-session ?
In Browser (client)
npm install express-session



Question: How to include express-session?
In Server(Node)
var session = require('express-session');
app.use(session({secret: 'this is secret key'}));