1. What is Node.js? What is it used for?

Does your candidate know the basics of Node.js? Ask this question to find out.

Node.js is a runtime JavaScript environment, which executes JavaScript code outside a web browser. It’s built on the V8 engine and uses a non-blocking, event-driven I/O model. Its package ecosystem is called npm.

Node.js is used for unified web application development because it represents a “JavaScript everywhere” paradigm.


2. What are the benefits of Node.js?

You’ll want to understand if candidates understand why they or you are working with Node.js. This question can give you valuable insights.

The benefits of Node.js are that it’s fast, asynchronous, scalable, open-source, and doesn’t buffer data.

Thanks to its non-blocking I/O and event-based model, it offers a short response time and concurrent processing. Other frameworks require developers to use thread management.

Chrome’s V8 engine also performs at the top level and is constantly improved. It helps make the Node.js library fast in code execution.

And as Node.js uses JavaScript both in the frontend and backend, development is much more agile. Plus, thanks to its open-source community, it’s constantly evolving.


3. What is Node.js mostly used for?

Node.js is mainly used for network programs like web servers. But it can also be used for different types of applications, including web applications and REST API server, and distributed systems.

Note: if you want to get a better understanding of how well candidates understand your needs, you can follow up with a question or steer the conversation in the direction of why you use Node.js.


4. What is event-driven programming?

Event-driven programming, which Node.js uses, is about building an application to respond to events. So when an event happens (say, a click), a callback function, which is registered to the element for that event, runs.

It’s the dominant paradigm used in graphical user interfaces.

However, the event-driven approach has also been criticized because it can lead to excessively complex code.


5. What is your experience with Node.js? Can you walk me through a recent project you worked on?

Obviously, there’s no right or wrong answer to this question. What you want is a bit of background on how a developer has used Node.js and their ability to communicate it.

You might need to probe a bit to get deeper into their story. “What happened next?” or “Can you tell me more about X?” work as follow-up questions.


6. What is an event loop in Node.js? How does it work?

An event loop is what handles all the async callbacks. When a listener is attached to an event and the event fires, the listener executes the callback.

When setTimeout, http.get and fs.readFile are called, Node.js continues these operations and other code without waiting for the output. However, when the operation finishes, it receives the output and runs callback functions one by one.


7. How does Node.js handle child threats?

Node.js doesn’t expose child threads to developers. Fundamentally, it’s a single thread process in order to support async processing.

However, behind the scenes it does spawn child threads for tasks, but they don’t block the main event loop or execute JavaScript code.


8. What are the types of API functions in Node.js?

Answer: 

There are two types of API functions in Node.js — asynchronous, non-blocking functions and synchronous, blocking functions.


9. Which tasks need to be done asynchronously using the event loop?

These tasks must be done asynchronously using the event loop:

  • I/O operations
  • Anything that requires blocking
  • Heavy computation

10. What are streams? How many are there in Node.js? Which events are fired by stream?

Streams are objects that let you write data to a destination continuously or read data from a source.

In Node.js, there are four streams:

  • Writable – for write operation
  • Readable – for read operation
  • Duplex – for both read and write operation
  • Transform – the output is computed based on input

1. What is Node.js? What is it used for?

Does your candidate know the basics of Node.js? Ask this question to find out.

Node.js is a runtime JavaScript environment, which executes JavaScript code outside a web browser. It’s built on the V8 engine and uses a non-blocking, event-driven I/O model. Its package ecosystem is called npm.

Node.js is used for unified web application development because it represents a “JavaScript everywhere” paradigm.


2. What are the benefits of Node.js?

You’ll want to understand if candidates understand why they or you are working with Node.js. This question can give you valuable insights.

The benefits of Node.js are that it’s fast, asynchronous, scalable, open-source, and doesn’t buffer data.

Thanks to its non-blocking I/O and event-based model, it offers a short response time and concurrent processing. Other frameworks require developers to use thread management.

Chrome’s V8 engine also performs at the top level and is constantly improved. It helps make the Node.js library fast in code execution.

And as Node.js uses JavaScript both in the frontend and backend, development is much more agile. Plus, thanks to its open-source community, it’s constantly evolving.


3. What is Node.js mostly used for?

Node.js is mainly used for network programs like web servers. But it can also be used for different types of applications, including web applications and REST API server, and distributed systems.

Note: if you want to get a better understanding of how well candidates understand your needs, you can follow up with a question or steer the conversation in the direction of why you use Node.js.


4. What is event-driven programming?

Event-driven programming, which Node.js uses, is about building an application to respond to events. So when an event happens (say, a click), a callback function, which is registered to the element for that event, runs.

It’s the dominant paradigm used in graphical user interfaces.

However, the event-driven approach has also been criticized because it can lead to excessively complex code.


5. What is your experience with Node.js? Can you walk me through a recent project you worked on?

Obviously, there’s no right or wrong answer to this question. What you want is a bit of background on how a developer has used Node.js and their ability to communicate it.

You might need to probe a bit to get deeper into their story. “What happened next?” or “Can you tell me more about X?” work as follow-up questions.


6. What is an event loop in Node.js? How does it work?

An event loop is what handles all the async callbacks. When a listener is attached to an event and the event fires, the listener executes the callback.

When setTimeout, http.get and fs.readFile are called, Node.js continues these operations and other code without waiting for the output. However, when the operation finishes, it receives the output and runs callback functions one by one.


7. How does Node.js handle child threats?

Node.js doesn’t expose child threads to developers. Fundamentally, it’s a single thread process in order to support async processing.

However, behind the scenes it does spawn child threads for tasks, but they don’t block the main event loop or execute JavaScript code.


8. What are the types of API functions in Node.js?

There are two types of API functions in Node.js — asynchronous, non-blocking functions and synchronous, blocking functions.


9. Which tasks need to be done asynchronously using the event loop?

These tasks must be done asynchronously using the event loop:

  • I/O operations
  • Anything that requires blocking
  • Heavy computation

10. What are streams? How many are there in Node.js? Which events are fired by stream?

Streams are objects that let you write data to a destination continuously or read data from a source.

In Node.js, there are four streams:

  • Writable – for write operation
  • Readable – for read operation
  • Duplex – for both read and write operation
  • Transform – the output is computed based on input

Q4. Is there any difference between JavaScript and Node.js?
Below are some significant differences between JavaScript and Node.js:

JavaScript Node.js
It is a programming language It works as an interpreter and environment for JavaScript
Runs on any web browser Runs on V8 (Chrome)
Follows the standards of Java programming language Node Js follows C++
Used for web application’s client-side activity Used for performing the non-blocking operation

Q5. Which are the most popular Node.js frameworks you have used?
Below is the list of frameworks that I have used:

Node.js Frameworks Description
AdonisJs Made up with SQL-database and supports No-SQL database including MongoDB
Express.js Helps in managing servers and routes and building lightweight applications
Meteor.js Assists in developing modern web and mobile applications
Nest.js Helps in creating effective and scalable server-side Node.js applications
Sails.js Assists in developing customized enterprise-grade applications and it is one of the highly recommended MVC node.js frameworks
Koa.js Known as next-generation framework having ECMAScript (ES6)

Q6. List some benefits of Node.js
Below are some benefits of Node.js:

Node.js Benefits
Scalable Applications are easy to scale in horizontal and vertical directions
Single Language It is one of the most efficient server-side JavaScript languages used for both front-end and back-end development.
Fullstack JS It is helpful in both client-side and server-side language
High-performing language It interprets JS code via Chrome’s V8 engine; hence it compiles JS code directly into the machine code and supports non-blocking I/O operations, which makes it a high-performing language
Cache benefits It supports caching of every single module in the application memory
Supports Common tools In Node.js, developers can get the support of commonly extended tools like Jasmin and unit-testing tools

Q7. Did you find any drawbacks in node.js?
Ans. Node.js has a major drawback: the Application Programming Interface (API) is sometimes unstable.


Q8. Do you keep track of Node.js trends?
Yes, as a developer, it is essential to comprehend frequent updates. Below are some interesting facts that caught my attention:

Now node.js is a serverless and hardware-free solution that will enhance its performance and productivity.

Maintenance of code in node.js is easy because of the microservices it offers.

js is helpful in giving strong backend support to real-time apps because it is an excellent data-serving platform supporting WebSockets protocols.

js holds a key position in IoT due to its data-centric approaches.


Q9. Do you think Node.js is better than PHP?
Both PHP and Node.js offer excellent programming experience to both developers and end-users. The main differences are –

PHP Node.js
Supported by a good number of hosting platforms and is easy to use It is more of a virtual server, and as it is younger than PHP, developers find it challenging to use
It provides a reliable and stable platform Speedy and quick turnaround time
The platform is less flexible The platform is highly flexible, agile, and scalable
Competent in handling CPU-intensive roles Less effective in handling CPU-intense activities
Stuck when the number of codes is huge Hardly gets stuck

Q10. State some features of Node.js v12.
Recently node.js v12 was launched in 2019, and some of its key highlights are:

  1. The V8 version is updated to 7.4
  2. The default HTTP parser is now redirected to IIhttp
  3. A new feature is introduced called “Diagnostic Reports”
  4. The error message has witnessed an update which points to checking the specific errors and failures
  5. js supports TLS1.3 as a default max protocol
  6. js can now trace asynchronous call frames due to its Async stack traces updates

Q11. Name some node.js applications.
Node.js applications are used in the below-mentioned domains:

  • Real-time applications
  • Network applications
  • Distributed systems

Q12. Name some companies that use node.js.
Ans. Some of the top companies using node.js are:

  • PayPal
  • LinkedIn
  • Yahoo, Mozilla
  • Netflix
  • Uber
  • eBay
  • Medium
  • NASA
  • Trello

Q13. Which performance metrics do you track for node.js?
It is essential to track performance metrics and evaluate node.js applications, including websites, web apps, mobile apps, enterprise apps, etc. Some of the parameters that one must determine are:

Metrics Description
Event Loop Checks the ability to execute code in a queue
Real-time behaviour Checks the response time of real-time applications
External frameworks Checks the response time, error rates, APIs, and request rates as node.js depends on several external frameworks
Process Memory Measures the time spent and runs memory on the helper tool called Garbage Collector

Q14. What is meant by Event-driven programming in Node.js?
Though node.js is a single-threaded programming application, it supports the concurrence of events and callbacks and uses an async function. Event-driven programming is designed on a concept to avoid collisions.

Whenever a user interacts on a webpage, an event recurs, and as a result, a change occurs on the user interface when an event triggers the associated function.


Q15. Which concepts are used in event-driven programming?
The following concepts are used in event-driven programming:

  • The callback function is called whenever an event triggers.
  • The main loop stays active, responds to each trigger, and calls the event handler for each event.

Q16. What do you mean by the Libuv platform?
It is a support library of Node.js and is a multi-platform used for asynchronous I/O. Some crucial features of Libuv are:

  • Backed with the full-featured event loop
  • Includes file system events
  • Supports child processes
  • Has asynchronous files & involves file system operations
  • Includes asynchronous TCP & UDP sockets

Q17. Have you heard of callback hell? What is it?
In Node.js, callback hell is used to return heavily nested callbacks that are complex and unreadable.


Q18. Which strategy works well for handling callback hell?
To handle callback hell, the below steps can be helpful:

  • Work on handling each error
  • Maintain simple codes
  • Split the complex codes into independent functions

Q19. What are API functions in node.js?
There are two types of functions:

  • Blocking function – The codes are blocked till the time the I/O event occurs
  • Non-blocking function – Several I/O calls are performed without blocking the entire program.

Q20. Name the different types of streams available in node.js.
Streams in Node.js are used to connect with each other to form a chain. There are four different types of streams in node.js:

<Readable>

<Writable>

<Duplex>

<Transform>


Q21. What do you mean by Globals?
Globals comprise of three different keywords:

  • Global – It acts as a container for global objects representing the global namespace.
  • Process – It is both a global object and an asynchronous function used to return information related to the application.
  • Buffer – It handles binary data as it is a class

Q22. How unhandled are exceptions caught in Node.js?
Using “Process,” a handler is attached for the “uncaughtException” event.


Q23. Define the test pyramid.
It gives an optimum ratio of unit tests, integration tests, and end-to-end tests a developer should use.


Q24. Define the way to secure HTTP cookies from XSS attacks.
This situation arrives when the attacker injects the JavaScript code into an HTML response. To mitigate such an unacceptable risk, the below steps can help:

Set flags using “set-cookie” HTTP header – HttpOnly and secure

Use code Set-Cookie: Set=<cookie-value>; HttpOnly


Q25. Find an error in this code:
Challenges in Life((resolve, reject) => { point out Error (‘error’) }).then(console.log)

This code will retrieve no error indication because the ‘catch’ function is missing before the ‘then’ function.


Q26. Write code using module.exports in Node.js.
Below is the code:

module.exports = {SayGoodNightInFrench; function () {return “Bonne Nuit”;},sayGoodNightInGerman: function () {Return “Gute Nacht”;}}; Copy code


Q27. How will you import the above code into a different file?
Below is the code for importing the code in a different file:

var wishes = require(“ ./wishes.js”);wishes. SayGoodNightInFrench(); // Bonne Nuitwishes. sayGoodNightInGerman(); // Gute NachtCopy code


Q28. Explain the term I/O.
Ans. I/O stands for Input/Output. It refers to the interaction of a program with the system’s disk and network. It represents any program, operation, or device that transfers data to or from one medium to another medium, such as a physical device, network, or files within a system.


Q29. Explain the control flow function.
Ans. The control flow function is a code that runs between several asynchronous function calls.


Q30. Name the arguments that async.queue takes as input.
Ans. The arguments are:

  • Task Function
  • Concurrency Value

Q31. What is the difference between Angular and Node.js?

Angular Js Node JS
Angular is an open-source web application development framework. It is a cross-platform run-time environment and system for applications.
It is written in JavaScript. Node.js is written in C, C++, and JavaScript programming languages.
AngularJS itself is a web application framework of JavaScript. Node js has various frameworks such as Express.js, Sails.js, and Partial.js.
It is primarily used for creating single-page client-side web applications. It is used for creating fast and scalable server-side networking applications.
Angular is suitable for building highly active and interactive web apps. It is suitable for small-size projects.
It is based on the model-view-controller design pattern. Node js is single-threaded.

Q32. Name some exit codes of Node.js.
Ans. The following are some exit codes of Node.js:

  • Unused
  • Fatal Error
  • Uncaught fatal exception
  • Internal Exception handler Run-time failure
  • Internal JavaScript Evaluation Failure

Q-1. What is Node.js?

Node.js is a JavaScript runtime or platform that is built on Google Chrome’s JavaScript v8 engine. This runtime allows executing the JavaScript code on any machine outside a browser (this means that it is the server that executes the Javascript and not the browser).

Node.js is single-threaded, that employs a concurrency model based on an event loop. It doesn’t block the execution instead registers a callback which allows the application to continue. Node.js can handle concurrent operations without creating multiple threads of execution so can scale pretty well.

It uses JavaScript along with C/C++ for things like interacting with the filesystem, starting up HTTP or TCP servers, and so on. Due to its extensively fast-growing community and NPM, Node.js has become a very popular, open-source, and cross-platform app. It allows the development of very fast and scalable network apps that can run on Microsoft Windows, Linux, or OS X.

Following are the areas where it’s perfect to use Node.js.

  • I/O bound Applications
  • Data Streaming Applications
  • Data Intensive Real-time Applications (DIRT)
  • JSON-based Applications
  • Single Page Applications

Q-2. What are the key features of Node.js?

Let’s look at some of the key features of Node.js.

  • Asynchronous event-driven IO helps concurrent request handling – All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response to the previous requests.
  • Fast in Code execution – Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence the processing of requests within Node.js also becomes faster.
  • Single Threaded but Highly Scalable – Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.
  • Node.js library uses JavaScript – This is another important aspect of Node.js from the developer’s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.
  • There is an Active and vibrant community for the Node.js framework – The active community always keeps the framework updated with the latest trends in web development.
  • No Buffering – Node.js applications never buffer any data. They simply output the data in chunks.

 


Q-3. Explain how do we decide, when to use Node.js and when not to use it.

When should we use Node.js?

It’s ideal to use Node.js for developing streaming or event-based real-time applications that require less CPU usage such as.

  • Chat applications.
  • Game servers.

Node.js is good for fast and high-performance servers, that face the need to handle thousands of user requests simultaneously.

Good for a collaborative environment.

It is suitable for environments where multiple people work together. For example, they post their documents and modify them by doing check-out and check-in of these documents.

Node.js supports such situations by creating an event loop for every change made to the document. The “Event loop” feature of Node.js enables it to handle multiple events simultaneously without getting blocked.

Advertisement servers.

Here again, we have servers that handle thousands of requests for downloading advertisements from a central host. And Node.js is an ideal solution to handle such tasks.

Streaming servers.

Another ideal scenario to use Node.js is for multimedia streaming servers where clients fire requests to the server to download different multimedia contents from it.

To summarize, it’s good to use Node.js when you need high levels of concurrency but less amount of dedicated CPU time.

Last but not least, since Node.js uses JavaScript internally, it fits best for building client-side applications that also use JavaScript.

When to not use Node.js?

However, we can use Node.js for a variety of applications. However, it is a single-threaded framework, so we should not use it for cases where the application requires a long processing time.

If the server is doing some calculations, it won’t be able to process any other requests. Hence, Node.js is best when processing needs less dedicated CPU time.


Q-4. What IDEs can you use for Node.js development?

Here is the list of the 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, and automated and safe refactorings. Additionally, we can use the debugger, VCS, terminal, and other tools present in the IDE.

JetBrains InteliJ 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. Its 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 a built-in browser.

Eclipse.

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

Atom.

It is an open-source application built with the integration of HTML, JavaScript, CSS, and Node.js. It works on top of the 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.


Q-5. Explain how Node.js works.

A Node.js application creates a single thread on its invocation. Whenever Node.js receives a request, it first completes its processing before moving on to the next request.

Node.js works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel. An Event Loop is a functionality that handles and processes all your external events and just converts them to a callback function. It invokes all the event handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request doesn’t have to wait if the processing is not complete.

While processing a request, Node.js attaches a callback function to it and moves it to the back end. Now, whenever its response is ready, an event is called which triggers the associated callback function to send this response.

Let’s take the example of grocery delivery.

Usually, the delivery boy goes to each and every house to deliver the packet. Node.js works in the same way and processes one request at a time. The problem arises when any one house is not open. The delivery boy can’t stop at one house and wait till it gets opened up. What he will do next, is to call the owner and ask him to call when the house is open. Meanwhile, he is going to other places for delivery. Node.js works in the same way. It doesn’t wait for the processing of the request to complete (the house is open). Instead, it attaches a callback function (call from the owner of the house) to it. Whenever the processing of a request completes (the house is open), an event gets called, which triggers the associated callback function to send the response.

To summarize, Node.js does not process the requests in parallel. Instead, all the back-end processes like I/O operations, and heavy computation tasks, that take a lot of time to execute, run in parallel with other requests.

Q-6. Explain REPL in Node.js.

The REPL stands for “Read Eval Print Loop”. It is a simple program that accepts the commands, evaluates them, and finally prints the results. REPL provides an environment similar to that of a Unix/Linux shell or a window console, in which we can enter the command, and the system, in turn, responds with the output. REPL performs the following tasks.

  • READ
    • It Reads the input from the user, parses it into JavaScript data structure, and then stores it in the memory.
  • EVAL
  • It Executes the data structure.
  • PRINT
  • It Prints the result obtained after evaluating the command.
  • LOOP
  • It Loops the above command until the user presses Ctrl+C two times.

 


Q-7. 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 number of requests asynchronously.

Moreover, Node.js has an optimized design that utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes on 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 the Node.js queue. As per the design, the main thread of the Node.js event loop will receive all of them and forward them to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on the event loop thread to pass the result back to the user.


Q-8. How to get Post Data in Node.js?

Following is the code snippet to fetch Post Data using Node.js.

app.use(express.bodyParser());app.post(‘/’, function(request, response){console.log(request.body.user);});


Q-9. How to make a Post request in Node.js?

The following code snippet can be used to make a Post Request in Node.js.

var request = require(‘request’);request.post(‘http://www.example.com/action’,{ form: { key: ‘value’ } },function (error, response, body) {if (!error && response.statusCode == 200) {console.log(body)}});


Q-10. What is Callback in Node.js?

We may call “callback” as an asynchronous equivalent for a function. Node.js makes heavy use of callbacks and triggers it at the completion of a given task. All the APIs of Node.js are written in such a way that they support callbacks.

For example, suppose we have a function to read a file, as soon as it starts reading the file, Node.js returns the control immediately to the execution environment so that the next instruction can be executed.

Once the file read operation is complete, it will call the callback function and pass the contents of the file as its arguments. Hence, there is no blocking or wait, due to File I/O.

This functionality makes Node.js highly scalable, using it processes a high number of requests without waiting for any function to return the expected result.


10 More Node.js Interview Questions
In the previous section, you covered the basics of Node.js. Let’s now dive a little deeper to check some intermediate-level Node.js interview questions.


Q-11. 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://coolcats.com/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 passes 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.


Q-12. How to avoid callback hell in Node.js?

Node.js internally uses a single-threaded event loop to process queued events. However, 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. The more the number of callbacks, the 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 take you a whole lot of time. There are four solutions that 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 an async mechanism.

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

The async module has <async.waterfall> API which passes data from one operation to another 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 the 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 a synchronous code into an asynchronous one.


Q-13. Can you create an HTTP Server in Nodejs, and explain the code used for it?

Yes, we can create an HTTP Server in Node.js. We can use the <http-server> command to do so.

Following is the sample code.

var http = require(‘http’);var requestListener = function (request, response) {response.writeHead(200, {‘Content-Type’: ‘text/plain’});response.end(‘Welcome Viewers\n’);}var server = http.createServer(requestListener);server.listen(8080); // The port where you want to start with.


Q-14. 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 advanced implementations 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’re to build an online employee management system, then we won’t do it using client-side JS. But Node.js can certainly do it as it runs on a server similar to Apache, and 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 number of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.

jQuery –

It is a famous JavaScript module that 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.


Q-15. What are Globals in Node.js?

There are three keywords in Node.js that it treats as Globals. These are Global, Process, and Buffer.

Global.

The Global keyword represents the global namespace object. It acts as a container for all other <global> objects. If we type <console.log(global)>, it’ll print out all of them.

An important point to note about the global objects is that not all of them are in the global scope, some of them fall in the module scope. So, it’s wise to declare them without using the var keyword or add them to the Global object.

Variables declared using the var keyword become local to the module whereas those declared without it get subscribed to the global object.

Process.

It is also one of the global objects but includes additional functionality to turn a synchronous function into an async callback. There is no limitation to access it from anywhere in the code. It is the instance of the EventEmitter class. Each node application object is an instance of the Process object.

It primarily gives back information about the application or the environment.

  • <process.execPath> – to get the execution path of the Node app.
  • <process.Version> – to get the Node version currently running.
  • <process.platform> – to get the server platform.

Some of the other useful Process methods are as follows.

  • <process.memoryUsage> – To know the memory used by the Node application.
  • <process.NextTick> – To attach a callback function that will get called during the next loop. It can cause a delay in executing a function.

Buffer.

The Buffer is a class in Node.js to handles binary data. It is similar to a list of integers but stores as raw memory outside the V8 heap.

We can convert JavaScript string objects into Buffers. However, it requires mentioning the encoding type explicitly.

  • <ascii> – Specifies 7-bit ASCII data.
  • <utf8> – Represents multibyte encoded Unicode charset.
  • <utf16le> – Indicates 2 or 4 bytes, little endian encoded Unicode chars.
  • <base64> – Used for Base64 string encoding.
  • <hex> – Encodes each byte as two hexadecimal chars.

Here is the syntax to use the Buffer class.

> var buffer = new Buffer(string, [encoding]);

The above command will allocate a new buffer holding the string with <utf8> as the default encoding. However, if you like to write a <string> to an existing buffer object, then use the following line of code.

> buffer.write(string)

This class also offers other methods like <readInt8> and <writeUInt8> that allow read/write from various types of data to the buffer.


Q-16. How to load HTML in Node.js?

To load HTML in Node.js we have to change the “Content-type” present in the HTML code from text/plain to text/html.

Let’s see an example where we have created a static file in a 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();});


Q-17. What is EventEmitter in Node.js?

The events module in Node.js allows us to create and handle custom events. The Event module contains an “EventEmitter” class which can be used to raise and handle custom events. It is accessible via the following code.

// Import events modulevar events = require(‘events’); // Create an eventEmitter objectvar eventEmitter = new events.EventEmitter();

When an EventEmitter instance encounters an error, it emits an “error” event. When a new listener gets added, it fires a “newListener” event and when a listener gets removed, it fires a “removeListener” event.

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


Q-18. How many types of Streams are present in Node.js?

Streams in Node.js are objects that allow reading data from a source or writing data to a specific destination in a continuous fashion. In Node.js, there are four types of streams.

  • <Readable> – This is the Stream to be used for the reading operation.
  • <Writable> – It facilitates the write operation.
  • <Duplex> – This Stream can be used for both the read and write operations.
  • <Transform> – It is a form of a duplex Stream, which performs the computations based on the available input.

All the Streams, discussed above are an instance of an “EventEmitter” class. The event thrown by the Stream varies with time. Some of the commonly used events are as follows.

  • <data> – This event gets fired when there is data available for reading.
  • <end> – The Stream fires this event when there is no more data to read.
  • <error> – This event gets fired when there is any error in reading or writing data.
  • <finish> – It fires this event after it has flushed all the data to the underlying system.

Q-19. List and Explain the important REPL commands.

Following is the list of some of the most commonly used REPL commands.

  • <.help> – It displays help for all the commands.
  • <tab Keys> – It displays the list of all the available commands.
  • <Up/Down Keys> – Its use is to determine what command was executed in REPL previously.
  • <.save filename> – Save the current REPL session to a file.
  • <.load filename> – To Load the specified file in the current REPL session.
  • <ctrl + c> – used to Terminate the current command.
  • <ctrl + c (twice)> – To Exit from the REPL.
  • <ctrl + d> – This command performs Exit from the REPL.
  • <.break> – It leads to Exiting from multiline expression.
  • <.clear> – Exit from multiline expression.

Q-20. What is NPM in Node.js?

NPM stands for Node Package Manager. It provides the following two main functionalities.

  • It works as an Online repository for node.js packages/modules which are present at <nodejs.org>.
  • It works as a Command line utility to install packages, and 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, the following is the command to install a famous Node.js web framework module called express-

$ npm install express

Let’s finally sum up this post with the last 10 Node.js Interview Questions…


10 Advanced Node.js Questions with Answers
Here are some of the advanced-level Node.js interview questions. These basically cover the key concepts so you will not only benefit in your interviews but also in your day-to-day project tasks,


Q-21. What is the global installation of dependencies?

Globally installed packages/dependencies are stored in <user-directory>/npm directory. Such dependencies can be used in the CLI (Command Line Interface) function of any node.js, but cannot be imported using require() in the Node application directly.

To install a Node project globally use the -g flag.

C:\Nodejs_WorkSpace>npm install express -g


Q-22. What is the local installation of dependencies?

By default, NPM installs any dependency in the local mode. It means that the package gets installed in the “node_modules” directory which is present in the same folder, where the Node application is placed. Locally deployed packages are accessible via require(). Following is the syntax to install a Node project locally.

C:\Nodejs_WorkSpace>npm install express


Q-23. What is package.json? Who uses it?

What is <package.json>?

  • It is a plain JSON (JavaScript Object Notation) text file that contains all metadata information about the 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 a “package” because the Node.js platform treats every feature as a separate component. Node.js calls these Packages or Modules.

Who uses it?

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

Q-24. Does Node.js support multi-core platforms? And is it capable of utilizing all the cores?

Yes, Node.js would run on a multi-core system without any issues. 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 additional hardware. It packages with a Cluster module which is capable of starting multiple Node.js worker processes that will share the same port.


Q-25. Which is the first argument usually passed to a Node.js callback handler?

Node.js core modules follow a standard signature for its callback handlers and usually, the first argument is an optional error object. And if there is no error, then the argument defaults to null or undefined.

Here is a sample signature for the Node.js callback handler.

function callback(error, results) {// Check for errors before handling results.if ( error ) {// Handle error and return.}// No error, continue with callback handling.}


Q-26. What is a chaining process in Node.js?

It’s an approach to connect the output of one stream to the input of another stream, thus creating a chain of multiple stream operations.


Q-27. How to create a custom directive in AngularJS?

To create a custom directive, we have to first register it with the application object by calling the <directive> function. While invoking the <register> method of <directive>, we need to give the name of the function implementing the logic for that directive.

For example, in the below code, we have created a copyright directive that returns a copyright text.

app.directive(‘myCopyRight’, function (){return{template: ‘@CopyRight MyDomain.com ‘};});

Note – A custom directive should follow the camel case format as shown above.


Q-28. 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 the following three methods to create a child process.

  • exec – <child_process.exec> 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.

Q-29. What are the different custom directive types in AngularJS?

AngularJS supports a number of different directives which also depend on the level we want to restrict them.

So in all, there are four different kinds of custom directives.

  • Element Directives (E)
  • Attribute Directives (A)
  • CSS Class Directives (C)
  • Comment Directives (M)

Q-30. What is a control flow function? What are the steps it executes?

It is a generic piece of code that runs in between several asynchronous function calls and is known as a control flow function.

It executes the following steps.

  • Control the order of execution.
  • Collect data.
  • Limit concurrency.
  • Call the next step in the program.
Back to list

Leave a Reply

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