Node.js Interview Questions Part - 2

7. Explain REPL in Node.js? List out some REPL command in Node.js?

Answer:

REPL stands for Read-Eval-Print-Loop. It is an interface which accepts the command, execute it and print the result. Node.js comes bundled with a REPL environment.

REPL can perform the following task.
  • Read
  • Eval
  • Print
  • Loop
Below are the REPL commands in Node.js.
  • Ctrl + c: terminate the current command.
  • Ctrl + c twice: it terminates the REPL.
  • Ctrl + d: terminates the REPL session.
  • Tab key: display the list of current available command.
  • .break: exit from the multiline expression.

8. What is module and what are the core modules in Node.js?

Answer:

Module is a set of function that we include in our application. Node.js encapsulates JavaScript related code into the single unit of code. Node.js has set of built-in module. We can include any built-in module in our application using require() function.

Example:
var http = require('http')

9. What are callback and callback hell and how to avoid it?

Answer:

Callback is like an asynchronous equivalent for a function. Node.js makes heavy use of callbacks and triggers them at the completion of a given task. All the APIs of Node.js are written in such a way that they support callbacks.

Node.Js works just like a courier boy. He goes to every house to deliver packets. If a person is not available, he calls the person and asks him to call when available. Similarly, Node.js attends one job at a time and doesn't wait for the processing of the request (delivering of packet) to complete. Instead, it attaches a callback function (call to the owner) to it. Whenever the processing of a request completes, an event gets called, which triggers the associated callback function to send the response.

Callback hell is heavily nested callbacks which make the code unreadable and difficult to maintain. Node.js uses a single-threaded event loop to process queued events. It uses callbacks to allow the code execution to continue past the long-running task. But more the no. of callbacks, longer the chain of returning callbacks would be. It's hard to debug the code and can cause you a whole lot of time.

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

10.  What is Cluster process module in Node.js?

Answer:

Node.js runs single threaded programming. But to take advantage of computer's multi-core systems, the Cluster module allows you to easily create child processes that each runs on their own single thread, to handle the load.

11.  Why Node.js is single threaded?

Answer:

Node.js was created with the believe that more performance and scalability can be achieved by doing async processing on a single thread than the typical thread based implementation.