NodeJS Interview Questions

1. Explain NodeJS?

Nodejs is a very powerful JavaScript-based framework/platform built on Google Chrome's  JavaScript V8 Engine. It is used to develop 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 millions of developers around the world. Node.js application are written in JavaScript.


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


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


4. Explain callback in NodeJS.

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.


5. 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)
})
 


6. What is callback hell in NodeJS?

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 calculations of data/fetching complex data. For example:

 

 
getUser(function(a){
  getUserPosts(a, function(b){
    getUserProjects(b, function(c){
      getMoreData(c, function(d){
        getMoreData(d, function(e){
          //...
        });
      });
    });
  });
});
 


7. How can you avoid callback hells?

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

  1. Modularization: break callbacks into independent functions
  2. Use a control flow library, like async
  3. Use generators with Promises
  4. Use async/await 


8. Explain the role of REPL in NodeJS.

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.  


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


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


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


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

  1. Readable - streams from which data can be read (for example fs.createReadStream()).
  2. Writable - streams to which data can be written (for example fs.createWriteStream()).
  3. Duplex - streams that are both Readable and Writable (for example net.Socket).
  4. Transform - Duplex streams that can modify or transform the data as it is written and read (for example zlib.createDeflate()).


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

 


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


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


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


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


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


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

event loop nodejs


20. What is EventEmitter?

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 emit. on property is used to bind a function with the event and emit is used to fire an event.


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


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


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


24. 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).


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


26. 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).


27. Explain the difference between operational error and programmer error?

Operation errors are the problems with the deployed server/system, like request timeout or hardware failure but programmer errors are actual bugs.


28. Who created Node.js and when was it initially released?

Ryan Dahl created NodeJS and it was initially released in 2009.


29. What is NPM?

NPM is a package manager for the JavaScript programming language. npm, Inc. is a subsidiary of GitHub, that provides hosting for software development and version control with the usage of Git. npm is the default package manager for the JavaScript runtime environment Node.js


30. Name few most popular Node.js frameworks?

Express, Loopback, Koa, Meteor, Sail.js etc


31. What is the alternative to the Node package manager (NPM)

yarn


32. What is the difference between dependencies and devDependencies in package.json?

dependencies are the list of npm packages that is necessary for a project to run,  ut devDependencies are the list of dependencies that are reuired only when development and testing.


33. What is the name of the JavaScript engine that Node.js is built upon?

Google Chrome V8 engine.


34. What is libuv in NodeJS?

Libuv is a cross-platform support library written in C. It was originally written to support Node.js, but now it is also used in Julia, Luvit, Neovim, etc… It is designed around the asynchronous event-driven model.


35. What is the purpose of process object?

It is used to get information on current process. Provides multiple events related to process activities.


36. What are streams in NodeJS?

Streams are objects that let you read data from a source or write data to a destination in the continuous fashion.


37. Where can we use Node.js?

  • Real-time applications
  • Collaborative tools
  • Data streaming applications
  • Networking applications


38. What is difference between put and patch?

PUT is mostly used for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

PATCH submits a partial modification to a resource. If it is needed to only update one field for the resource, you should use the PATCH method.


39. What is Express.js and What are the advantages of Express.js?

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It has been called the de facto standard server framework for Node.js.

Advantages of Express.js

  1. Easy to configure and customize.
  2. Makes Node.js application development fast and easy.
  3. Easy to connect with databases such as MongoDB, Redis, MySQL
  4. Easy to define an error handling middleware or normal middleware.
  5. Easy to integrate with different template engines like Jade, Vash, EJS etc.


40. how to make use of all CPUs while working with Node.js?

As Node.js is single-threaded, So normally it uses the single core of the CPU, doesn't take full advantage of multi-core systems. To use all resources of the multi-core systems you can use Cluster module. Clustering in Node.js allows you to create separate processes(as per the number of core available in the system) that can share the same server port.


41. What are globals in Node.js?

Global, Process, and Buffer.


42. What is process.nextTick() in NodeJS?

In Node.js, each iteration of an Event Loop is called a tick. To schedule a callback function to be invoked in the next iteration of the Event Loop, we use process.nextTick(). It just takes a callback with no time bound, since it will be executing in the next iteration of the Event Loop.


43. Difference between setTimeout() and process.nextTick()

The difference between setTimeout() and process.nextTick() is that the process.nextTick() function is specific to the Node.js Event Loop, But setTimeout() uses JavaScript runtime to schedule its own queue of events.


44. What is the difference between process.nextTick() and setImmediate()?

process.nextTick() is used to schedule a callback function to be invoked in the next iteration of the Event Loop whereas setImmediate() executes a callback on the next cycle of the event loop and it gives back to the event loop for executing any I/O operations.


45. When we use process.nextTick ( ) ?

  • To allow users to handle errors.
  • To cleanup unwanted resources.
  • To try a request to run before starting the next iteration of event loop.
  • Allow a callback to run after call stack and before next iteration of event loop.


46. What is Memcached? How to Implement Memcached in Nodejs Application?

Memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read. Memcached is free and open-source software, licensed under the Revised BSD licence. Memcached runs on Unix-like operating systems (at least LINUX and OS X) and on Microsoft windows. How to Implement Memcached in Nodejs Application