15 Commonly Asked NodeJS Interview Questions

15 Commonly Asked NodeJS Interview Questions

Preparation is as important as your knowledge for a successful programming interview. It’ll give you the confidence to attend the interview without the nerves of uncertainty. This is especially true if you are facing a programming interview for the first time in your life.

To help Node.js developers achieve this necessary preparedness for an interview, I have put together a list of 15 commonly asked Node.js and web development related interview questions. These questions and their answers will also prompt you to brush up on any area you feel needing improvement before the big interview.

In this post, we are focusing on questions related to only Node.js; however, bear in mind that JavaScript-related questions are very common among Node.js interviews, so it doesn’t hurt that you prepare some of those as well. We wrote a post not so long ago on common Javascript interview questions to cover all your bases.

Right now, let’s dive in to see the Node-related questions you are likely to get in your next interview.


How Is Node.js Different from Javascript?

JavascriptNode.js
Javascript is a programming language that runs in any web browser that has a suitable browser engine.Node.js is an interpreter and a runtime environment designed for Javascript. Node.js comes with some in-built modules that enhance the features of Javascript programming.
Outside of Node.js, Javascript is used on the client-side of a web application, especially for developing dynamic features.Node.js can be used on any operating system to develop applications that interact with system hardware, particularly for web backends.
Javascript can run on different browser engines like V8 (Google Chrome), Spider Monkey (Firefox), and Javascript Core (Safari).Node.js only runs on the V8 engine used by Chrome.

When Should and Shouldn’t You Use Node.js?

Node.js is asynchronous, event-driven, non-blocking, and single-threaded. It makes Node a perfect candidate for developing the following types of applications:

  • Realtime applications like chat and live update providing applications.
  • Streaming applications that stream video or other multimedia content to a large audience.
  • Other I/O intensive applications like collaborative platforms.
  • Web backends that follow microservices architecture.

However, Node.js’ unique qualities make it not an ideal choice for some other types of applications. Applications that carry out CPU-intensive tasks like complex mathematical computations do not bode well with Node.js because of its single-threaded execution.

If you want to learn more about this, check out our article Node.js architecture and when to use Node.js in projects .


What Does EventEmitter Do?

Every object in Node.js capable of emitting events is a member of the EventEmitter class. http module is one such example.

All EventEmitter classes can use the eventEmitter.on() function to attach event listeners to the event. Then, as soon as such an event is caught, its listeners are called one by one synchronously.

const events = require("events");
const eventEmitter = new events.EventEmitter();

const eventListener = function(){
console.log("event triggered");
}

eventEmitter.on("emitted", eventListener);

eventEmitter.emit("emitted");

What Is Node’s Event Loop?

Since Node.js is single-threaded, it has to be non-blocking to prevent the thread from spending too long on a task that takes a long time to complete. The event loop is responsible for achieving this non-blocking behavior.

Its job is scheduling the pending tasks using the application thread.

We know that Node uses callbacks to handle the response returned by an asynchronous function when its task is complete. Similar to the event that created the task, the completion of the task also emits an event. Node.js adds these events that require handling to an event queue.

The event loop iterates over events in the event queue and schedules when to execute their associated callback functions.


What Are Node Streams?

Streams are pipelines that read or write data from a source and transfer it to a continuous flow destination. There are four types of streams:

  • Readable
  • Writable
  • Duplex (both readable and writable)
  • Transform (A type of duplex stream. Its output is calculated using the input)

Each stream is also an EventEmitter. It means a stream object can emit events when there are no data on the stream, when data is available on the stream, or when data in the stream is flushed from the program.

const fs = require("fs");
const readableStream = fs.createReadStream("test.txt");
let content = "";

readableStream.on("data", (chunk) => {
  content += chunk;
});

readableStream.on("end", () => {
  console.log(content);
});

What Is the Difference between ReadFile and CreateReadStream Functions?

readFile function reads the entire content of the file asynchronously and stores it in the memory before passing it to the user.

createReadStream uses a readable stream that would read the file chunk by chunk without storing the entirety of it into the memory.

createReadStream optimizes the file reading operation compared to readFile by using less memory and making it faster. If the file is of considerable size, the user doesn’t have to wait a long time until it’s entire content is available because small chunks are sent to the user as they are read.

const fs = require("fs");

fs.readFile("test.txt", (err, content) => {
  console.log( content);
});

How Do You Handle Uncaught Exceptions in Node.js?

We can catch the uncaught exceptions thrown in the application in its process level. We attach a listener to the process global object to catch such events.

process.on("uncaughtException", (err) => {
  console.log("exception caught: ", err);
});

Can Node Take Full Advantage of a Multi-Processor System?

Node applications are always single-threaded. So, naturally, the application uses only a single processor even when running on multi-processor systems.

But one of Node’s core modules, Cluster, provides support for Node applications to take advantage of multiple cores. It allows us to create multiple worker processes that can run on several cores parallelly and share a single port to listen to events.

Here, each process uses IPC to communicate with the main thread and pass the server handle to others as needed. The main process can either listen to the port itself and pass every new connection to child processes in a round-robin order or assign the port to child processes so the child processes listen to requests.


What Is the Reactor Design Pattern Used in Node.js?

The reactor pattern is used for maintaining non-blocking I/O operations in Node.js. It attaches a callback function (a handler) to each I/O operation. The handler is then submitted to a demultiplexer at the time of the request creation.

Demultiplexer collects every I/O request made in the application and queues them as events in a queue. This queue is what we call the event queue. After queuing the event, the demultiplexer returns the control of the application thread.

Meanwhile, the event loop iterates over each event in the event queue and invokes the attached callback to handle the event response.

This is the reactor pattern used by Node.js.


What Are the Benefits of a Single-Threaded Web Backend to a Multi-Threaded One?

Though Node is single-threaded, most of the programming languages used for backend development provides multiple threads to handle application operations. In what way is having only a single thread is beneficial to backend development?

  • It’s easier for developers to implement the application. Our application has no risk of running into unexpected race conditions suddenly while in production.
  • Single-threaded applications are easily scalable.
  • They can serve a large number of user requests received at a moment without much delay. In comparison, a multi-threaded backend has to wait for a thread from the thread pool to be free to serve the user request when the traffic is high. With the Node’s non-blocking nature, there’s no risk of a user request hanging on to the single thread for too long (this is true only when the operations are not CPU-intensive).

What Is REPL in Node?

REPL stands for Read-Eval-Print-Loop. It is a virtual environment where you can run a programming language easily. Node comes with a built-in REPL to run Javascript code. It is similar to the consoles we use in browsers to run Javascript code.

To start the Node REPL, you just have to run the command, node, on the command-line. Then, once you write a Javascript line of code in one line, you can see its output in the next.


What Is the Difference between Process.nextTick and SetImmediate Functions?

The callback passed to the setImmediate function is executed in the next iteration of the event loop over the event queue.

On the other hand, the callback passed to the process.nextTick is executed before the next iteration of the event loop, and after the operation currently running in the program is finished. At the application start, its callback is called before the event loop starts iterating over the event queue.

Therefore, the callback of process.nextTick is always called before that of setImmediate.

If we consider the following code snippet:

setImmediate(() => {
  console.log("first");
})

process.nextTick(() => {
  console.log("second");
})

console.log("third");

Its output is printed in the following order.

third
second
first

What Are Stubs?

Stubs are used when testing applications. They simulate the behavior of a given component or a module so that you can only focus on the part of the code you want to test. By using stubs in place of components irrelevant to the test, you won’t have to worry about external components impacting the result of the test.

For example, if the component you are testing has a file reading operation before the part you expect to test, you can use a stub to simulate that behavior and return a mock content without actually reading the file.

In Node, we use libraries like Sinon for this purpose.


Why Is It a Good Practice to Separate ‘App’ and ‘Server’ in Express?

By separating app and server in Express, we can separate the API implementation from the network-related configuration. This allows us to carry out API tests without performing network calls. This also guaranteed faster test execution and better code coverage metrics.

To achieve this separation, you should declare API and server in separate files. Here we use two files: app.js and server.js.

//app.js
const express = require("express");
const app = express();

app.use("/", index);
app.use("/contact", contact);
app.use("/user", user);

module.exports = app;

//server.js
const http = require("http");
const app = require("/app/JobBoard/JobListModule");

app.set('port', process.env.PORT);

const http = http.createServer(app);

What Are Yarn and Npm? Why Would You Want to Use Yarn over Npm?

npm is the default package manager distributed with Node.js. It has a large library of public and private packages stored in a database called emp registry that users can access via npm’s command-line client. With the help of npm, users can easily manage dependencies used in a project.

yarn is also a package manager that was released as an answer to some of npm’s shortcomings. However, yarn relies on the npm registry to provide users access to packages. Since yarn’s underlying structure is based on npm itself, your project structure and workflow doesn’t have to go through major changes if you are migrating to yarn from npm.

Like I mentioned before, yarn provides better functionality over npm in some cases. Unlike npm, it caches every package you download, so you don’t have to redownload it whenever needed.

It also provides better security by verifying the integrity of packages using checksums. It guarantees a package that worked on a certain system will work exactly the same way in any other system. These are some of the reasons why you would want to choose yarn over npm for package management.


Conclusion

In this post, we went through 15 of the most commonly asked Node.js interview questions to help you prepare better for your next interview. Knowing what type of questions you are likely to get asked and knowing their answers will give you the confidence to answer interview questions without doubts and nerves.

Whenever you face that big interview, we wish you the best of luck for it to be a successful one!

If you liked what you saw, please support my work!

Anjalee Sudasinghe - Author @ Live Code Stream

Anjalee Sudasinghe

I’m a software engineering student who loves web development. I also have a habit of automating everyday stuff with code. I’ve discovered I love writing about programming as much as actual programming.

I’m extremely lucky to join the Live Code Stream community as a writer and share my love for programming with others one article at a time.