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){

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

//Print the buffer

//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

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) ?

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.on('data', function(chunk) {
    textdata += chunk;
readerStream.on('end', function() {
    console.log('All data are:'+textdata);
readerStream.on('error', function(err) {

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");'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

Get dirname