On
node js interview questions answers




As a MEAN stack developer and if you have an interview lined up then just read the top 10 Node.js interview questions we are posting here.
All of our questions are thoroughly researched and have a potential to surface in most Node.js interviews.


1. Is Node.Js Entirely Based On A Single-Thread? 


Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously. Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers. To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.

2. How To Make Post Request In Node.Js?

var request = require('request'); 
request.post('http://www.livescript.in/postData', { form: { key: 'value' } }, 
  function (error, response, body) { 
     if (!error && response.statusCode == 200) {    
       console.log(body) ;
    } 
 }
);

3. What Is Callback Hell?

Initially, you may praise Callback after learning about it. Callback hell is heavily nested callbacks which make the code unreadable and difficult to maintain. Let’s see the following code example.
downloadPhoto('http://livescript.in/cat.gif', displayPhoto);

function displayPhoto (error, photo) { 
       if (error) {
         console.error('Download error!', error) 
       } else {
         console.log('Download finished', photo) 
       }
 }
 console.log('Download started');


In this scenario, Node.js first declares the “displayPhoto” function.
After that, it calls the “downloadPhoto” function and pass the “displayPhoto” function as its callback.
Finally, the code prints ‘Download started’ on the console. The “displayPhoto” will be executed only after “downloadPhoto” completes the execution of all its tasks.

4. How To Avoid Callback Hell In Node.Js?

Node.js internally uses a single-threaded event loop to process queued events. But this approach may lead to blocking the entire process if there is a task running longer than expected. Node.js addresses this problem by incorporating callbacks also known as higher-order functions. So whenever a long-running process finishes its execution, it triggers the callback associated. With this approach, it can allow the code execution to continue past the long-running task. However, the above solution looks extremely promising. But sometimes, it could lead to complex and unreadable code. More the no. of callbacks, longer the chain of returning callbacks would be. Just see the below example. With such an unprecedented complexity, it’s hard to debug the code and can cause you a whole lot of time. There are four solutions which can address the callback hell problem.

1. Make Your Program Modular.

It proposes to split the logic into smaller modules. And then join them together from the main module to achieve the desired result.

2. Use Async Mechanism.

It is a widely used Node.js module which provides a sequential flow of execution. The async module has <async.waterfall> API which passes data from one operation to other using the next callback. Another async API <async.map> allows iterating over a list of items in parallel and calls back with another list of results. With the async approach, the caller’s callback gets called only once. The caller here is the main method using the async module.

3. Use Promises Mechanism.

Promises give an alternate way to write async code. They either return the result of execution or the error/exception. Implementing promises requires the use of .then() function which waits for the promise object to return. It takes two optional arguments, both functions. Depending on the state of the promise only one of them will get called. The first function call proceeds if the promise gets fulfilled. However, if the promise gets rejected, then the second function will get called.

4. Use Generators.

Generators are lightweight routines, they make a function wait and resume via the yield keyword. Generator functions use a special syntax function*. They can also suspend and resume asynchronous operations using constructs such as promises or thunks and turn asynchronous code into asynchronous.

5. What Is The Difference Between Nodejs, AJAX, And JQuery?

The one common trait between Node.js, AJAX, and jQuery is that all of them are the advanced implementation of JavaScript. However, they serve completely different purposes.

Node.Js 

It is a server-side platform for developing client-server applications. For example, if we’ve to build an online employee management system, then we won’t do it using client-side JS. But the Node.js can certainly do it as it runs on a server similar to Apache, Django not in a browser.

AJAX (Aka Asynchronous Javascript And XML) –

It is a client-side scripting technique, primarily designed for rendering the contents of a page without refreshing it. There are a no. of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.

JQuery –

It is a famous JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development. However, it’s not mandatory to use it but as it also manages cross-browser compatibility, so can help you produce highly maintainable web applications.  

6. How To Load HTML In Node.Js?

To load HTML in Node.js we have to change the “Content-type” in the HTML code from text/plain to text/HTML. Let’s see an example where we have created a static file in web server.

fs.readFile(filename, "binary", function(err, file) { 
  if(err) { 
     response.writeHead(500, {"Content-Type": "text/plain"});
     response.write(err + "\n");
     response.end(); 
     return;
   }

 response.writeHead(200);
 response.write(file, "binary");
 response.end(); 

});


Now we will modify this code to load an HTML page instead of plain text.

fs.readFile(filename, "binary", function(err, file) {
  if(err) { 
    response.writeHead(500, {"Content-Type": "text/html"});
    response.write(err + "\n");
    response.end(); 
    return;
 }

 response.writeHead(200, {"Content-Type": "text/html"});
 response.write(file);
 response.end();
 
});

7. What Is NPM In Node.Js?

NPM stands for Node Package Manager. It provides following two main functionalities.
  • It works as an Online repository for node.js packages/modules which are present at <nodejs.org>.
  • It works as Command line utility to install packages, do version management and dependency management of Node.js packages.
NPM comes bundled along with Node.js installable. We can verify its version using the following command-
$ npm --version
NPM helps to install any Node.js module using the following command.
$ npm install <Module Name>
For example, following is the command to install a famous Node.js web framework module called express-
$ npm install express

8. What Is Package.Json? Who Uses It? What Is Package.json file?

  • It is a plain JSON (JavaScript Object Notation) text file which contains all metadata information about Node.js Project or application.
  • This file should be present in the root directory of every Node.js Package or Module to describe its metadata in JSON format.
  • The file is named as “package” because Node.js platform treats every feature as a separate component. Node.js calls these as Package or Module.

Who Use It?

  • NPM (Node Package Manager) uses <package.json> file. It includes details of the Node.js application or package. This file contains a no. of different directives or elements. These directives guide NPM, about how to handle a module or package.

9. What Is A Child_process Module In Node.Js?

Node.js supports the creation of child processes to help in parallel processing along with the event-driven model. The Child processes always have three streams <child.stdin>, child.stdout, and child.stderr. The <stdio> stream of the parent process shares the streams of the child process. Node.js provides a <child_process> module which supports following three methods to create a child process.
  • exec – child_process.exec the method runs a command in a shell/console and buffers the output.
  • spawn – child_process.spawn launches a new process with a given command.
  • fork – child_process.fork is a special case of the spawn() method to create child processes.

10. What Is A Control Flow Function? What Are The Steps Does It Execute?

It is a generic piece of code which runs in between several asynchronous function calls is known as control flow function. It executes the following steps.
  • Control the order of execution.
  • Collect data.
  • Limit concurrency.
  • Call the next step in the program.