Blog Post

Images
Interview Questions For Node.js

Interview Questions For Node.js

1. What is “callback hell” and how can it be avoided?

Ans: “Callback hell” refers to heavily nested callbacks that have become unweildy or unreadable.

An example of heavily nested code is below:

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

        }

      });

    });

  });

});

The primary method to fix callback hell is usually referred to as modularization. The callbacks are broken out into independent functions which can be called with some parameters. So the first level of improvement 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);

Even though this code is much easier to read, and we created some functions that we can even reuse later, in some cases it may be appropriate to use a more robust solution in the form of promises. Promises allow additional desirable behavior such as error propogation and chaining. Node.js doesn’t include much core support for promises, so one of the popular promise libraries such as Q promise library should be used.

More information about promises and how they work can be found here.

Additionally, a more supercharged solution to callback hell is provided by generators, as these can resolve execution dependency between different callbacks. However, generators are much more advanced and it might be overkill to use them for this purpose.

2. How does Node.js handle child threads?

Ans: Node.js, in its essence, is a single thread process. It does not expose child threads and thread management methods to the developer. Technically, Node.js does spawn child threads for certain tasks such as asynchronous I/O, but these run behind the scenes and do not execute any application JavaScript code, nor block the main event loop.

If threading support is desired in a Node.js application, there are tools available to enable it, such as the ChildProcess module.

3. What is the preferred method of resolving unhandled exceptions in Node.js?

Ans: Unhandled exceptions in Node.js can be caught at the Process level by attaching a handler for uncaughtException event.

process.on('uncaughtException', function(err) {

  console.log('Caught exception: ' + err);

});

However, uncaughtException is a very crude mechanism for exception handling and may be removed from Node.js in the future. An exception that has bubbled all the way up to the Process level means that your application, and Node.js may be in an undefined state, and the only sensible approach would be to restart everything.

The preferred way is to add another layer between your application and the Node.js process which is called the domain.

Domains provide a way to handle multiple different I/O operations as a single group. So, by having your application, or part of it, running in a separate domain, you can safely handle exceptions at the domain level, before they reach the Process level.

4. How does Node.js support multi-processor platforms, and does it fully utilize all processor resources?

Ans: Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.

5. What is typically the first argument passed to a Node.js callback handler?

Ans: Node.js core modules, as well as most of the community-published ones, follow a pattern whereby the first argument to any callback handler is an optional error object. If there is no error, the argument will be null or undefined.

A typical callback handler could therefore perform error handling 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

}

6. Consider following code snippet:

{

    console.time("loop");

    for (var i = 0; i < 1000000; i += 1){

        // Do nothing

    }

    console.timeEnd("loop");

}

The time required to run this code in Google Chrome is considerably more than the time required to run it in Node.js. Explain why this is so, even though both use the v8 JavaScript Engine.

Ans: Within a web browser such as Chrome, declaring the variable i outside of any function’s scope makes it global and therefore binds it as a property of the window object. As a result, running this code in a web browser requires repeatedly resolving the property i within the heavily populated window namespace in each iteration of the for loop.

In Node.js, however, declaring any variable outside of any function’s scope binds it only to the module’s own scope (not the window object) which therefore makes it much easier and faster to resolve.

7. What is difference between synchronous and asynchronous method of fs module?

Ans: Every method in fs module have synchronous as well as asynchronous form. Asynchronous methods takes a last parameter as completion function callback and first parameter of the callback function is error. It is preferred to use asynchronous method instead of synchronous method as former never block the program execution where the latter one does.

8. What is ‘Callback’ in node.js?

Ans: 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.

9. What does it mean “non-blocking” in node.js?

Ans: 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.

10. What is callback hell in Node.js?

Ans: 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");

        }

      });

    });

  });

});

11. Why is Node.js Single-threaded?

Ans: 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.

12. What is stream and explain types of streams?

Ans: Streams are a collection of data that might not be available all at once and don’t have to fit in memory. Streams provide chunks of data in a continuous manner. It is useful to read a large set of data and process it.

There is 4 fundamental type of streams:

  • Readable
  • Writeable
  • Duplex
  • Transform

Readable streams as the name suggest used in reading a large chunk of data from a source. Writable streams are used in writing a large chunk of data to the destination.

Duplex streams are both readable and writable ( Eg socket). Transform stream is the duplex stream which is used in modifying the data (eg zip creation).

13. What is npm? What is the main functionality of npm?

Ans: npm stands for Node Package Manager. Following are the two main functionalities of npm:

  • Online repositories for node.js packages/modules which are searchable on search.nodejs.org
  • Command line utility to install packages, do version management and dependency management of Node.js packages.

14. Can You Create HTTP Server In Nodejs, Explain The Code Used For It?

Ans: Yes, we can create HTTP Server in Node.js. We can use the <http-server> command to do so.

Following is the sample code.

var http = require('http');

var requestListener = function (request, response) {

response.writeHead(200, {'Content-Type': 'text/plain'});

response.end('Welcome Viewers\n');

}

var server = http.createServer(requestListener);

server.listen(8080); // The port where you want to start with.

15. What is the difference between global installation of dependencies and local installation of dependencies?

Ans: Global installation of dependencies are stored in /npm directory. While local installation of dependencies is stored 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.

Globally deployed packages cannot be imported using require() in Node application directly. On the other hand locally deployed packages are accessible via require().

To install a Node project globally -g flag is used.

C:\Nodejs_WorkSpace>npm install express ?g  

To install a Node project locally, the syntax is:

C:\Nodejs_WorkSpace>npm install express