NodeJs

1)      What is node.js?
Node.js is a Server side scripting which is used to build scalable programs. Its multiple advantages over other server side languages, the prominent being non-blocking I/O.
2)      How node.js works?
Node.js works on a v8 environment, it is a virtual machine that utilizes JavaScript as its scripting language and achieves high output via non-blocking I/O and single threaded event loop.
3)      What do you mean by the term I/O ?
I/O is the shorthand for input and output, and it will access anything outside of your application. It will be loaded into the machine memory to run the program, once the application is started.
4)      What does event-driven programming mean?
In computer programming, event driven programming is a programming paradigm in which the flow of the program is determined by events like messages from other programs or threads. It is an application architecture technique divided into two sections 1) Event Selection 2) Event Handling
5)      Where can we use node.js?
Node.js can be used for the following purposes
a)      Web applications ( especially real-time web apps )
b)      Network applications
c)       Distributed systems
d)      General purpose applications
6)      What is the advantage of using node.js?
a)      It provides an easy way to build scalable network programs
b)      Generally fast
c)       Great concurrency
d)      Asynchronous everything
e)      Almost never blocks
7)      What are the two types of API functions in Node.js ?
The two types of API functions in Node.js are
a)      Asynchronous, non-blocking functions
b)      Synchronous, blocking functions
8)      What is control flow function?
A generic piece of code which runs in between several asynchronous function calls is known as control flow function.
9)      Explain the steps how “Control Flow” controls the functions calls?
a)      Control the order of execution
b)      Collect data
c)       Limit concurrency
d)      Call the next step in program
10)   Why Node.js is single threaded?
For async processing, Node.js was created explicitly as an experiment. It is believed that more performance and scalability can be achieved by doing async processing on a single thread under typical web loads than the typical thread based implementation.
11)   Does node run on windows?
Yes – it does. Download the MSI installer from http://nodejs.org/download/
12)   Can you access DOM in node?
No, you cannot access DOM in node.
13)   Using the event loop what are the tasks that should be done asynchronously?
a)      I/O operations
b)      Heavy computation
c)       Anything requiring blocking
14)   Why node.js is quickly gaining attention from JAVA programmers?
Node.js is quickly gaining attention as it is a loop based server for JavaScript. Node.js gives user the ability to write the JavaScript on the server, which has access to things like HTTP stack, file I/O, TCP and databases.
15)   What are the two arguments that async.queue takes?
The two arguments that async.queue takes
a)      Task function
b)      Concurrency value
16)   What is an event loop in Node.js ?
To process and handle external events and to convert them into callback invocations an event loop is used. So, at I/O calls, node.js can switch from one request to another .
17)   Mention the steps by which you can async in Node.js?
By following steps you can async Node.js
a)      First class functions
b)      Function composition
c)       Callback Counters
d)      Event loops
18)    What are the pros and cons of Node.js?
Pros:
a)      If your application does not have any CPU intensive computation, you can build it in Javascript top to bottom, even down to the database level if you use JSON storage object DB like MongoDB.
b)      Crawlers receive a full-rendered HTML response, which is far more SEO friendly rather than a single page application or a websockets app run on top of Node.js.
Cons:
a)       Any intensive CPU computation will block node.js responsiveness, so a threaded platform is a better approach.
b)      Using relational database with Node.js is considered less favourable
19)   How Node.js overcomes the problem of blocking of I/O operations?
Node.js solves this problem by putting the event based model at its core, using an event loop instead of threads.
20)   What is the difference between Node.js vs Ajax?
The difference between Node.js and Ajax is that, Ajax (short for Asynchronous Javascript and XML) is a client side technology, often used for updating the contents of the page without refreshing it. While,Node.js is Server Side Javascript, used for developing server software. Node.js does not execute in the browser but by the server.
21)   What are the Challenges with Node.js ?
Emphasizing on the technical side, it’s a bit of challenge in Node.js to have one process with one thread to scale up on multi core server.
22)    What does it mean “non-blocking” in node.js?
In node.js “non-blocking” means that its IO is non-blocking.  Node uses “libuv” to handle its IO in a platform-agnostic way. On windows, it uses completion ports for unix it uses epoll or kqueue etc. So, it makes a non-blocking request and upon a request, it queues it within the event loop which call the JavaScript ‘callback’ on the main JavaScript thread.
23)   What is the command that is used in node.js to import external libraries?
Command “require” is used for importing external libraries, for example, “var http=require (“http”)”.  This will load the http library and the single exported object through the http variable.
24)   Mention the framework most commonly used in node.js?
“Express” is the most common framework used in node.js
25)   What is ‘Callback’ in node.js?
Callback function is used in node.js to deal with multiple requests made to the server. Like if you have a large file which is going to take a long time for a server to read and if you don’t want a server to get engage in reading that large file while dealing with other requests, call back function is used. Call back function allows the server to deal with pending request first and call a function when it is finished.
26. What is Node.js? Where can you use it?
Node.js is a server side scripting based on Google’s V8 JavaScript engine. It is used to build scalable programs especially web applications that are computationally simple but are frequently accessed.   
You can use Node.js in developing I/O intensive web applications like video streaming sites. You can also use it for developing: Real-time web applications, Network applications, General-purpose applications and Distributed systems.

27. Why use Node.js?
Node.js makes building scalable network programs easy. Some of its advantages include:
  • It is generally fast
  • It almost never blocks
  • It offers a unified programming language and data type
  • Everything is asynchronous 
  • It yields great concurrency

28. What are the features of Node.js?
Node.js is a single-threaded but highly scalable system that utilizes JavaScript as its scripting language. It uses asynchronous, event-driven I/O instead of separate processes or threads. It is able to achieve high output via single-threaded event loop and non-blocking I/O.

29. How else can the JavaScript code below be written using Node.Js to produce the same output?
console.log("first");
setTimeout(function() {
    console.log("second");
}, 0);
console.log("third");
Output:
first
third
second
In Node.js version 0.10 or higher, setImmediate(fn) will be used in place of setTimeout(fn,0) since it is faster. As such, the code can be written as follows:
console.log("first");
setImmediate(function(){
    console.log("second");
});
console.log("third");

30. How do you update NPM to a new version in Node.js?
You use the following commands to update NPM to a new version:
$ 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

31. Why is Node.js Single-threaded?
Node.js is single-threaded for async processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved as opposed to the typical thread-based implementation. 

32. Explain callback in Node.js.
A callback function is called at the completion of a given task. This allows other code to be run in the meantime and prevents any blocking.  Being an asynchronous platform, Node.js heavily relies on callback. All APIs of Node are written to support callbacks. 

33. What is callback hell in Node.js?
Callback hell is the result of heavily nested callbacks that make the code not only unreadable but also difficult to maintain. For example:
query("SELECT clientId FROM clients WHERE clientName='picanteverde';", function(id){
  query("SELECT * FROM transactions WHERE clientId=" + id, function(transactions){
    transactions.each(function(transac){
      query("UPDATE transactions SET value = " + (transac.value*0.1) + " WHERE id=" + transac.id, function(error){
        if(!error){
          console.log("success!!");
        }else{
          console.log("error");
        }
      });
    });
  });
});

34. How do you prevent/fix callback hell?
The three ways to prevent/fix callback hell are:
  • Handle every single error
  • Keep your code shallow
  • Modularize – split the callbacks into smaller, independent functions that can be called with some parameters then joining them to achieve desired results.
The first level of improving the code above might be:
var logError = function(error){
    if(!error){
      console.log("success!!");
    }else{
      console.log("error");
    }
  },
  updateTransaction = function(t){
    query("UPDATE transactions SET value = " + (t.value*0.1) + " WHERE id=" + t.id, logError);
  },
  handleTransactions = function(transactions){
    transactions.each(updateTransaction);
  },
  handleClient = function(id){
    query("SELECT * FROM transactions WHERE clientId=" + id, handleTransactions);
  };
query("SELECT clientId FROM clients WHERE clientName='picanteverde';",handleClient);
You can also use Promises, Generators and Async functions to fix callback hell.

35. Explain the role of REPL in Node.js.
As the name suggests, REPL (Read Eval print Loop) performs the tasks of – Read, Evaluate, Print and Loop. The REPL in Node.js is used to execute ad-hoc Javascript statements. The REPL shell allows entry to javascript directly into a shell prompt and evaluates the results. For the purpose of testing, debugging, or experimenting, REPL is very critical.  

36. Name the types of API functions in Node.js.
There are two types of functions in Node.js.:
  • Blocking functions - In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously
For example:
const fs = require('fs');
const data = fs.readFileSync('/file.md'); // blocks here until file is read
console.log(data);
// moreWork(); will run after console.log
The second line of code blocks the execution of additional JavaScript until the entire file is read. moreWork () will only be called after Console.log
  • Non-blocking functions - In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted.  Non-blocking functions execute asynchronously. 
For example:
const fs = require('fs');
fs.readFile('/file.md', (err, data) => {
  if (err) throw err;
  console.log(data);
});
// moreWork(); will run before console.log
Since fs.readFile () is non-blocking, moreWork () does not have to wait for the file read to complete before being called. This allows for higher throughput. 

37. Which is the first argument typically passed to a Node.js callback handler?
Typically, the first argument to any callback handler is an optional error object. The argument is null or undefined if there is no error. 
Error handling by a typical callback handler could be as follows:
function callback(err, results) {
    // usually we'll check for the error before handling results
    if(err) {
        // handle error somehow and return
    }
    // no error, perform standard callback handling
}

38. What are the functionalities of NPM in Node.js?
NPM (Node package Manager) provides two functionalities:
  • Online repository for Node.js packages
  • Command line utility for installing packages, version management and dependency management of Node.js packages
39. What is the difference between Node.js and Ajax?
Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced implementation of JavaScript. They all serve completely different purposes.  
Ajax is primarily designed for dynamically updating a particular section of a page’s content, without having to update the entire page. 
Node.js is used for developing client-server applications.

40. Explain chaining in Node.js.
Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations. 

41. What are “streams” in Node.js? Explain the different types of streams present in Node.js.
Streams are objects that allow reading of data from the source and writing of data to the destination as a continuous process.
There are four types of streams.
  •   to facilitate the reading operation
  • to facilitate the writing operation
  • to facilitate both read and write operations
  • is a form of Duplex stream that performs computations based on the available input 

42. What are exit codes in Node.js? List some exit codes. 
Exit codes are specific codes that are used to end a “process” (a global object used to represent a node process). 
Examples of exit codes include:
  • Unused
  • Uncaught Fatal Exception
  • Fatal Error
  • Non-function Internal Exception Handler
  • Internal Exception handler Run-Time Failure
  • Internal JavaScript Evaluation Failure

43. What are Globals in Node.js?
Three keywords in Node.js constitute as Globals. These are:
  • Global – it represents the Global namespace object and acts as a container for all otherobjects.
  • Process – It is one of the global objects but can turn a synchronous function into an async callback. It can be accessed from anywhere in the code and it primarily gives back information about the application or the environment. 
  • Buffer – it is a class in Node.js to handle binary data. 
44. What is the difference between AngularJS and Node.js?
Angular.JS is a web application development framework while Node.js is a runtime system. 

45. Why is consistent style important and what tools can be used to assure it?
Consistent style helps team members modify projects easily without having to get used to a new style every time. Tools that can help include Standard and ESLint. 

3 comments:

  1. Enjoyed reading the article above, really explains everything in detail, the article is very interesting and effective. Thank you and good luck for the upcoming articles nodejs certification

    ReplyDelete
  2. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    Digital Marketing Training in Chennai

    Digital Marketing Course in Chennai

    ReplyDelete