Node Js Interview Questions And Answers

1. Why use Node.js?
Answer: It is used to develop I/O intensive web applications like video streaming sites, single-page applications (SPA), and other web applications. Node.js is open-source and used by thousands of developers around the world.

2. What is REPL and explain its role in Node.js?
Answer: REPL or Read Eval Print Loop are the tasks as per their names like for reading, evaluation, printing, and looping. Ad-hoc JavaScript statements are executed through REPL. It allows direct entry to the JavaScript shell prompt and the result also gets evaluated. REPL is important for testing, debugging, and experimenting.

3. Explain the difference between Ajax and Node.js?
Answer: Ajax is asynchronous javascript and XML and is the advanced implementation of JavaScript just like Node, js. They both serve purely different purposes.

Ajax is defined and designed to update a particular section of a web page, in which users need not update the complete web page, and a page section is usually updated dynamically in Ajax technology.

4. Can you list on port 80 with Node, if yes then how?
Answer: Well, programmers must not try to listen on port 80 with Node JS, you need superuser rights to do so. This is always better to avoid this practice. But still, if you want to listen to this port then you can do it by running the application firstly on the port number above 1024 and then by putting Nginx like a reverse proxy.

5. Explain Node.js web application architecture?
Answer: 
A web application distinguishes into 4 layers:

Client Layer: The Client layer contains web browsers, mobile browsers or applications which can make an HTTP request to the webserver.

Server Layer: The Server layer contains the Web server which can intercept the request made by clients and pass them the response.

Business Layer: The business layer contains application server which is utilized by the webserver to do required processing.

This layer interacts with the data layer via a database or some external programs.

Data Layer: The Data layer contains databases or any source of data.

Node.js web layer

6. What is the difference between Node.js and Ajax?
Answer:

  • Node.js and Ajax (Asynchronous JavaScript and XML) are the advanced implementations 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. 

7. What are LTS releases of Node.js why should you care?
Answer:

  • An LTS(Long Term Support) version of Node.js receives all the critical bug fixes, security updates and performance improvements.
  • LTS versions of Node.js are supported for at least 18 months and are indicated by even version numbers (e.g. 4, 6, 8). They’re best for production since the LTS release line is focussed on stability and security, whereas the Current release line has a shorter lifespan and more frequent updates to the code. Changes to LTS versions are limited to bug fixes for stability, security updates, possible npm updates, documentation updates and certain performance improvements that can be demonstrated to not break existing applications. (node js interview questions and answers for experienced)

8. What IDEs Can You Use For Node.Js Development?
Answer:
Here is the list of most commonly used IDEs for developing node.js applications.

Cloud9:

It is a free, cloud-based IDE that supports, application development, using popular programming languages like Node.js, PHP, C++, Meteor and more. It provides a powerful online code editor that enables a developer to write, run and debug the app code.

JetBrains WebStorm:

WebStorm is a lightweight yet powerful JavaScript IDE, perfectly equipped for doing client-side and server-side development using Node.js. The IDE provides features like intelligent code completion, navigation, automated and safe refactorings. Additionally, we can use the debugger, VCS, terminal and other tools present in the IDE.

JetBrains IntelliJ IDEA:

It is a robust IDE that supports web application development using mainstream technologies like Node.js, Angular.js, JavaScript, HTML5 and more. To enable the IDE that can do Node.js development we have to install a Node.js plugin. It provides features, including syntax highlighting, code assistance, code completion and more. We can even run and debug Node.js apps and see the results right in the IDE. It’s JavaScript debugger offers conditional breakpoints, expression evaluation, and other features.

Komodo IDE:

It is a cross-platform IDE that supports development in main programming languages, like Node.js, Ruby, PHP, JavaScript and more. It offers a variety of features, including syntax highlighting, keyboard shortcuts, collapsible Pane, workspace, auto indenting, code folding and code preview using built-in browser.

Eclipse:

It is a popular cloud-based IDE for web development using Java, PHP, C++ and more. You can easily avail the features of Eclipse IDE using the Node.js plug-in, which is. 

Atom:

It is an open-source application built with the integration of HTML, JavaScript, CSS, and Node.js. It works on top of Electron framework to develop cross-platform apps using web technologies. Atom comes pre-installed with four UI and eight syntax themes in both dark and light colors. We can also install themes created by the Atom community or create our own if required.

9. How To Avoid Callback Hell In Node.Js?
Answer: 
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.

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.

Use Async Mechanism:

It is a widely used Node.js module which provides a sequential flow of execution.

The async module has API which passes data from one operation to another using the next callback.

Another async API 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.

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.

Use Generators:

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

10. Explain the event loop in Node Js?
Answer: 
In Node Js processes are single-threaded, to supports concurrency it uses events and callbacks. An event loop is a mechanism that allows Node.js to perform non-blocking I/O operations.

11. Explain chaining in Node.js?
Answer: 
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 The Differences Between “Readuintbe” IN Node? Js?
Answer: 
ReadUIntBE:  It’s a generalized version of all numeric read methods, which supports up to 48 bits accuracy. Setting noAssert to “true” to skip the validation.

writeIntBE:  This will write the value to the buffer at the specified byte length and offset and it supports up to 48 bits of accuracy.

13. What do you mean by Asynchronous API?
Answer: 
All APIs of Node.js library are asynchronous that is non-blocking. It essentially means a Node.js based server never waits for an 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 a response from the previous API call.

14. Explain callback in Node.js?
Answer: The callback is called once the asynchronous operation has been completed. Node.js heavily uses callbacks and all API’s of Node.js are written to support callbacks. 

15. What is chaining in Node js, explain it?
Answer: When the output of one stream gets connected to another stream as input to create a chain of multiple operations then it is called chaining. It is just a mechanism to define multiple operations. 

16. Explain the event loops of Node.js?
Answer: Node.js runs through a single thread as per Node.js developer, but in real Node.js uses many threads through libuv. Every I/O require callbacks when you will put them into an event loop for execution. So, a chain of events is known as an event loop.

17. What do you understand by the term I/O?
Answer: I/O stands for input and output. It accesses anything outside of your application. It loaded into the machine memory to run the program, once the application starts.

18. What is the role of assert in Node.js?
Answer: The Node.js Assert is a way to write tests. It provides no feedback when running your test unless one fails. The assert module provides a simple set of assertion tests that can be used to test invariants. The module is intended for internal use by Node.js, but can be used in application code via require (‘assert’).

19. What is the difference between events and callbacks in Node.js?
Answer: Although, Events and Callbacks look similar to the differences lies in the fact that callback functions are called when an asynchronous function returns its result whereas event handling works on the observer pattern. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through the events module and EventEmitter class which is used to bind events and event listeners.

20. Explain the role of REPL in Node.js?
Answer: 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.

21. Why is consistent style important and what tools can be used to assure it?
Answer: 
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.

22. Explain what is Reactor Pattern in Node.js?
Answer:

  • Reactor Pattern is an idea of non-blocking I/O operations in Node.js. This pattern provides a handler(in case of Node.js, a callback function) that is associated with each I/O operation. When an I/O request is generated, it is submitted to a demultiplexer.
  • This demultiplexer is a notification interface that is used to handle concurrency in non-blocking I/O mode and collects every request in the form of an event and queues each event in a queue. Thus, the demultiplexer provides the Event Queue.
  • At the same time, there is an Event Loop which iterates over the items in the Event Queue. Every event has a callback function associated with it, and that callback function is invoked when the Event Loop iterates. (Online training institute)

23. What are the timing features of Node.js?
Answer: 
The Timers module in Node.js contains functions that execute code after a set period of time.

set Time out/clear Time out:  can be used to schedule code execution after a designated amount of milliseconds

set Interval/clear Interval: can be used to execute a block of code multiple times

set Immediate/clear Immediate: will execute code at the end of the current event loop cycle

process. next Tick: used to schedule a callback function to be invoked in the next iteration of the Event Loop

24. What is the difference between the process?nextTick() and setImmediate()?
Answer: The difference between the process.nextTick() and setImmediate() is that process.nextTick() defers the execution of an action till the next pass around the event loop or it simply calls the callback function once the ongoing execution of the event loop is finished 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.

25. What Is The Difference Between Nodejs, AJAX, And JQuery?
Answer:
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.

26. What Is The Global Installation Of Dependencies?
Answer: 
Globally installed packages/dependencies are stored in /npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js, but cannot be imported using require() in the Node application directly.

27. Explain the role of the Callback function in Node.js?
Answer: 
In Node.js, the Callback function is used to cater to multiple requests made to the server. If there is a large file that is expected to take the server a long time to process, the Callback function can be invoked to ensure that other requests to the server are uninterrupted.

28. Name some of the attributes of package.json?
Answer:

Following are the attributes of Package.json

  • name:  Name of the package
  • version: a version of the package
  • description:  Description of the package
  • homepage: homepage of the package
  • author: author of the package
  • contributors:  name of the contributors to the package
  • dependencies:  list of dependencies. npm automatically installs all the dependencies mentioned here in the node_module folder of the package.
  • repository: repository type and URL of the package
  • main: entry point of the package
  • keywords: keywords

29. Does Node.Js Support Multi-Core Platforms? And Is It Capable Of Utilizing All The Cores?
Answer:

  • Yes, Node.js would run on a multi-core system without any issue. But it is by default a single-threaded application, so it can’t completely utilize the multi-core system.
  • However, Node.js can facilitate deployment on multi-core systems where it does use the additional hardware. It packages with a Cluster module which is capable of starting multiple Node.js worker processes that will share the same port.

30. What are ACID properties wrt to a database?
Answer:

  • ACID stands for Atomicity, Consistency, Isolation, and Durability.
  • Atomicity-
  • It means that either the record/document updates completely or does not update with respect to the operation.
  • Either everything occurs or nothing occurs.
  • Consistency-
  • It implies that a transaction either creates a new and valid state of data or, if any failure occurs, returns all data to its state before the transaction was started.
  • If successful then valid data else revert back to original data.
  • Isolation-
  • Two or more simultaneous database queries should run independently of the other transactions.
  • Durability-
  • Data once committed should be saved in memory so that even in case of system failure, data is not affected.
  • This article on GeeksforGeeks explains this concept very nicely.

31. Where and why should you not use NodeJS?
Answer:

Now this one is a pretty interesting question. I have heard answers like:

  • “NodeJS should not be used because it is not secure as other low-level language-based web servers as it uses JavaScript which is a client-side scripting language”
  • To everyone out there, this is NOT the reason. You can make NodeJS servers as secure as you want. It depends on your requirements and your code.
  • To answer this question, NodeJS should NOT be used where computations are CPU intensive. Eg: Data Analytics Server, Image Processing Servers, Video Processing Servers, etc.
  • NodeJS is meant for highly I/O-bound operations which do not require heavy CPU intensive operation/tasks.
  • Some Additional facts which you may be asked:
  • MongoDB is not ACID compliant
  • This means that MongoDB does not guarantee any of the ACID properties.
  • NodeJS is a Runtime Environment. It is NOT a JavaScript framework.

32. What is an event loop in Node.js?
Answer: 
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. 

33. What is tracking?
Answer:

  • This is the basic Node.js Interview Questions that are asked in an interview. Tracing enables you to trace information generated by V8. It can be enabled by passing the flag as:
  • trace-events-enabled while starting the node. All these categories that are recorded can be specified by
  • the flag –trace-event-categories. The logs that are enabled can be opened as chrome://tracing in Chrome.

34. Explain the NPM functionalities in Node.js?
Answer:

NPM is Node package manager that provides below-listed two functionalities:

js packages online repository Command-line utility to install packages, dependency management and version management of these packages of Node.js

35. Define stub in Node.js?
Answer: Stubs programs or functions are used to stimulate module or component behavior. Canned answers of the functions are provided by stubs during any test case. You can also ensure why these stubs are called.

36. What are the advantages of Node.js?
Answer:

  • Node.js is an open source, a cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript and can be run within the Node.jsruntime on OS X, Microsoft Windows, Linux, FreeBSD, NonStop and IBM.
  • Advantages:
  • Web development is done in a dynamic language (JavaScript) on a VM that is incredibly fast (V8). It is much faster than Ruby, Python, or Perl.
  • Ability to handle thousands of concurrent connections with minimal overhead on a single process.
    JavaScript is perfect for event loops with first-class function objects and closures. People already know how to use it this way having used it in the browser to respond to user-initiated events.
  • Many people already know JavaScript, even people who do not claim to be programmers. It is arguably the most popular programming language.
  • Using JavaScript on a web server as well as the browser reduces the impedance mismatch between the two programming environments that can communicate data structures via JSON that work the same on both sides of the equation. Duplicate form validation code can be shared between server and client and so on. 

37. What is Closure?
Answer:

  • The closure is a function defined within another scope that has access to all the variables within the outer scope. A Closure allows us a free environment for the outer function to access the inner functions and inner variables without any scope restrictions.
  • The closure is the local variable for a function, kept alive after the function has returned; or it’s a stack-frame that is not deallocated when the function returns. A Closure is an inner function that has access to the outer function variable’s scope chain. The Closure has 3 scope chains; the first one is to access to its own scope (variables defined within the curly brackets) and the second one is to access the outer function’s variables and the third one is to access the global variables.
  • Points to remember about Closures,
  • Whenever you use a function inside another function, a Closure is used.
  • Closure in JavaScript is like keeping a copy of all the local variables.
  • A Closure is created just on entry to a function and the local variables are added to that Closure.
  • A new set of local variables are kept every time a function with a Closure is called.
  • The closure is the term for both the functions along with the variables that are captured.

38. Explain Process Object in Node.js?
Answer: The process object is the global object in Node. It can be accessed from anywhere; it is an instance of EventEmitter. Each Node.js has a set of built-in functionalities, accessible through the global process object. The process object provides the standard input/output (stdio) streams stdin, stdout, and stderr (as in C/C++) as in the following:

stdin-

A readable stream for reading input from the user.

stdout-

A writable stream, either synchronously or asynchronously.

stderr-

A blocking synchronous writable stream intended for error messages.
The stdout or non-blocking functions are: console.log, console.info, util.puts, util.print and Stderr. The blocking functons are: console.warn, console.error, util.debug and process.stdin (a readable stream for getting user input).

Properties of Process Object-

process.title

By default a process title is NODE but you can change it.

Notepad-

process.title-

39. Explain Colors Module in Node.js?
Answer: 
The color module uses popular color.js. Since the color module is not a built-in module of node.js, we need to install it using the node package manager.

npm install colors:

Once the command has executed successfully, you will find the following screen. In my case, it’s showing that the colors module was successfully installed in the application and is ready for use.

npm install colors:

The beauty of the colors module is that we can beautify the output with various colors. Here is the link to the colors module in NPM.

40. What are Request and Cheerio in Node.js NPM?
Answer: 
Request and Cheerio are our npm packages. Cheerio doesn’t try to emulate a full implementation of the DOM. It specifically focuses on the scenario where you want to manipulate an HTML document using jQuery-like syntax. As such, it compares to jsdom favorably in some cases, but not in every situation.

Cheerio itself doesn’t include a mechanism for making HTTP requests, and that’s something that can be tedious to handle manually. It’s a bit easier to use a module called request to facilitate requesting remote HTML documents. Request handles common tasks like caching cookies between multiple requests, setting the content length on POSTs, and generally makes life easier. 

41. How can you perform Testing in Node JS?
Answer:

  • To check whether our Node JS is working, we can create a “Hello World” program in either of the following two ways,
  • Directly type a message into the command window.
    Type the message in a JavaScript file and execute it in the node.
    Directly typing a message in a command window
  • Open your command window (press the Window key + R ), type cmd in the window. Now a window will be opened, you can type your commands into it.
  • Directly typing a message
  • Once you pointed out to your drive as shown in the image, type “node” and press Enter. Now you can type anything in your console using console.log. Then you will get the output as shown in the preceding image.

42. How can you create HTTPS Server WithNodeJS?
Answer: We use HTTPS when we need secure sessions. A secure session implies that the web browser will encrypt everything you do with a digitally signed certificate. So obviously before you do HTTPS, you need to create certificates. Let’s, therefore, spend some time to see how to create certificates for SSL.

43. What is Asynchronous Programming?
Answer: 
Every function in node.js is asynchronous which means that everything that would normally block the thread is instead executed in the background, in other words, it continues running in the background and the flow of control moves to the next line and executes them; the moment the operation is completed it executes a callback that will then be executed. For example, if you are reading a file on the file system then you need to specify a callback function that is executed when the read operation has completed. 

44. What are the key points of Node.js?
Answer:

  • These are the key points about Node.js,
  • Node.js is nothing but server-side JavaScript.
  • Single-threaded environment.
  • Asynchronous event driven server-side JavaScript.
  • Runs on Google JS ver-8 Engine.
  • Nonblocking I/O and File API.
  • Highly scalable.
  • Nodes apps are created.
  • Achieving Scale and Concurrency
  • Written in C and C++
  • A file in node.js is called a Module.
  • High performance.

45. Why Node.js is single-threaded?
Answer: 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.

46. What is the event loop in JavaScript?
Answer: 
Event loop, as the name suggests is loop which runs in the background listening for various event emitters.

47. Explain “Console” in Node.JS?
Answer: “Console” is a global object and will be used for printing to stderr and stdout and this will be used in a synchronous manner in case of destination is either file or terminal or else it is used in an asynchronous manner when it is a pipe.

48. What is Cluster Worker Object in Node.js?
Answer: 
A Worker Object is a script that runs in a background process and does not block the other code processes attached to the page. A Worker object contains all the public information and methods about a worker. The master can use “cluster.workers.” If a worker throws an exception and does not handle the exception itself, the exception will create an event that you can listen for as an error event.

49. What is Web Scraping in Node.js?
Answer: 
Web Scraping is the software technique of extracting the information from server-side web applications. In this article, we will see how things work by simply creating a web scraper using the DOM Parsing technique, and the tool which I am using is Node.js.

crape Data From Html is our function and we create variables in the function for every item that we want to scrape from the website and then the data is serialized from our website in JSON format and then we have it once deserialization is done. In this case, the circular red region gives me its relative node in the inspect window.

50. What does it mean “non-blocking” in node.js?
Answer: 
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 poll or kqueue, etc. So, it makes a non-blocking request and upon a request, it queues it within the event loop which calls the JavaScript ‘callback’ on the main JavaScript thread.

51. Explain the steps of how “Control Flow” controls the functions calls?
Answer:

  • Control the order of execution
  • Collect data
  • Limit concurrency
  • Call the next step in the ra

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email