NodeJS Interview Questions

Q1. Explain nodejs?

 

Nodejs is a very powerful JavaScript-based framework/platfrom built on Google Chrome's  JavaScript V8 Engine. It is used to develope I/O intensive web applications like video streaming sites, single-page applications, and other web applications. Node.js is open source, completely free, and used by thousands of developers around the world. Node.js applicaion are written in JavaScript.



Q2. Explain key features in nodejs.

Below are the key features of nodejs:

1. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, which means non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.

2. Very Fast Execution − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.

3. Single Threaded − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as compared to the  other traditional servers.



Q3. Explain the main reasons of using nodejs.

Node.js makes building scalable network programs easy. Some of its advantages include:

 

1. It is generally fast

2. It almost never blocks

3. It offers a unified programming language and data type

4. Everything is asynchronous

5. It yields great concurrency



Q4. 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.

 

For example, a function to read a file may start reading file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high number of requests without waiting for any function to return results.



Q5. What is an error-first callback?

Error-first callbacks are used to pass errors and data as well. You have to pass the error as the first parameter, and it has to be checked to see if something went wrong. Additional arguments are used to pass data.

 

fs.readFile(filePath, function(err, data) {  

 if (err) {

   // handle the error, the return is important here

   // so execution stops here

   return console.log(err)

 }

 // use the data object

 console.log(data)

})



Q6. What is callback hell in Node.js?

Callback hell is the result of heavily nested callbacks that make our code not only unreadable but also difficult to maintain. Such situation mainly occurs while playing with heavy calucations of data/fetching complex data. 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");

       }

     });

   });

 });

});

 



Q7. How can you avoid callback hells?

There are lots of ways to solve the issue of callback hells:

 

modularization: break callbacks into independent functions

use a control flow library, like async

use generators with Promises

use async/await (note that it is only available in the latest v7 release



Q8. 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.  



Q9. What are the functionalities of NPM in Node.js?

NPM (Node package Manager) provides two functionalities:

 

a. Online repository for Node.js packages

 

b. Command line utility for installing packages, version management and dependency management of Node.js packages

 



Q10. 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.

 



Q11. 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.



Q12. What are “streams” in Node.js? Explain the different types of streams present in Node.js.

A stream is an abstract interface for working with streaming data in Node.js. The stream module provides a base API that makes it easy to build objects that implement the stream interface.

 

There are many stream objects provided by Node.js. For instance, a request to an HTTP server and process.stdout are both stream instances.

Streams can be readable, writable, or both. All streams are instances of EventEmitter.

 

The stream module can be accessed using:

 

const stream = require('stream');

Types of Streams#

There are four fundamental stream types within Node.js:

 

a. Readable - streams from which data can be read (for example fs.createReadStream()).

b. Writable - streams to which data can be written (for example fs.createWriteStream()).

c. Duplex - streams that are both Readable and Writable (for example net.Socket).

d. Transform - Duplex streams that can modify or transform the data as it is written and read (for example zlib.createDeflate()).



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

 

a. Unused

b. Uncaught Fatal Exception

c. Fatal Error

d. Non-function Internal Exception Handler

e. Internal Exception handler Run-Time Failure

f. Internal JavaScript Evaluation Failure



Q14. How does Node.js handle child threads?

 

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.



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

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.



Q16. What do you mean by Asynchronous API?

 

All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.



Q17. What is global installation of dependencies?

Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag.



Q18. What is local installation of dependencies?

 

By default, npm installs any dependency 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. Locally deployed packages are accessible via require(). To install a Node project locally following is the syntax.



Q19. What is Event Loop?

 

Node js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed.



Q20. What is Event Emmitter?

EventEmitter class lies in events module. It is accessibly via following syntax:

//import events module
var events = require('events');
//create an eventEmitter object
var eventEmitter = new events.EventEmitter();

When an EventEmitter instance faces any error, it emits an 'error' event. When new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.

EventEmitter provides multiple properties like on and emiton property is used to bind a function with the event and emit is used to fire an event.



Q21. What is purpose of Buffer class in Node?

 

Buffer class is a global class and can be accessed in application without importing buffer module. A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.



Q22. What is Piping in Node?

 

Piping is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations. Consider the above example, where we've read test.txt using readerStream and write test1.txt using writerStream. Now we'll use the piping to simplify our operation or reading from one file and writing to another file.



Q23. Name some of the events fired by streams.

Each type of Stream is an EventEmitter instance and throws several events at different instance of times. For example, some of the commonly used events are:

 

data - This event is fired when there is data is available to read.

end - This event is fired when there is no more data to read.

error - This event is fired when there is any error receiving or writing data.

 

finish - This event is fired when all data has been flushed to underlying system



Q24. How will you open a file using Node?

 

Following is the syntax of the method to open a file in asynchronous mode:

fs.open(path, flags[, mode], callback)

Parameters

Here is the description of the parameters used:

  • path - This is string having file name including path.

  • flags - Flag tells the behavior of the file to be opened. All possible values have been mentioned below.

  • mode - This sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.

  • callback - This is the callback function which gets two arguments (err, fd).



Q25. What is the purpose of setTimeout function?

The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.

 

This function returns an opaque value that represents the timer which can be used to clear the timer.



Q26. What is the purpose of setInterval function?

The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.

 

This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t).