Nodejs interview questions

Top 15 Nodejs Interview Questions – 2022

After attending a lot of interviews, I have compiled all the frequently asked Nodejs interview questions. Following are the top 15 nodejs interview questions I was asked. The questions comprise basic, intermediate, and advanced level questions.

1. What is Nodejs?

Ans – Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine. It is used to develop APIs on the server side. NoSQL and SQL databases can be used. This language has a large number of libraries.

2. Is Nodejs single-threaded or multiple threaded?

Ans – It is single-threaded. Single-threaded processes contain the execution of instructions in a single sequence. In other words, one command is processed at a time.

3. If Nodejs is single-threaded, how does it handle multiple asynchronous processes?

Ans – Although Nodejs is single-threaded, it works on an event loop model. The event loop is a never-ending loop that keeps on consuming the upcoming processes. In the event loop, there is a queue that manages upcoming async processes and there is a listener at the end. The event loop consists of different types of phases which handle async functions passing through it. Using event loop, the main thread assigns different threads to different async processes which help in the execution of each process.

4. How does Nodejs handle concurrency?

Ans – Concurrency is handled by libuv library in nodejs. Let’s say there are 10 concurrent processes coming up, libuv library will set up a thread pool that will assign threads to each process.

5. How can you improve the performance of Nodejs?

Ans – The most common way of improving the performance of Nodejs is by clustering. By default, a single nodejs process uses a single-core processor which handles all the async activities. By clustering, we start multiple instances of nodejs on multiple core processors which results in multiple event loops and improved performance. When multiple instances are created, a cluster manager comes into play which monitors each instance of nodejs.

6. What is an event emitter in Nodejs?

Ans – Nodejs has an event emitter class that is capable of emitting events. To implement it, let’s say, we create an object called emitter and then we write emitter.on(‘func’) to create the event. Finally, emitter.emit(‘func’) function emits the function func.

7. What are the common error codes in an API?

Ans – Following are the common error codes:

  • 404 Not Found. It means the server could not find the requested resource.
  • 401 Unauthorized. This status code means you haven’t yet authenticated against the API.
  • 403 Forbidden. It means that the client who is requesting is known to the server but does not have access.
  • 400 Bad Request. It occurs due to syntax errors.
  • 429 Too Many Requests. It happens when a user sends too many requests in a period of time.
  • 500 Internal Server Error. The server encountered an unexpected error.
  • 503 Service Unavailable. The server is not ready to handle the request.

8. Is Nodejs created for handling async processes or sync processes?

Ans – The main objective of nodejs is to handle processes in an async manner.

9. If Nodejs works in an async manner, Can we make it work in a sync manner?

Ans – Yes. We can make the nodejs work in a sync manner. One of the most famous ways of doing it is by using the await keyword. The await keyword makes the nodejs to wait for a function to complete before it moves forward which is a synchronous behavior.

10. What is callback hell and how to avoid it?

Ans – A callback function is a function passed into another function as an argument, which is then invoked inside the parent function to complete some kind of action. We can write a callback within a callback such that it will become a nested callback which is eventually called callback hell.

Writing nested callbacks is not a good practice and it is advised to be avoided by developers as it reduces code readability and proper maintenance. To avoid it, we use promise.

11. What is a promise and how does it solve the problem of callback hell?

Ans – A Promise in Nodejs means an action that will either be completed or rejected. A Nodejs Promise is a placeholder for a value that will be available in the future, allowing us to handle the result of an asynchronous task once it has completed or encountered an error. Promises make writing asynchronous code easier. They’re an improvement on the callback pattern. 

Promises make error handling across multiple asynchronous calls more effortless than callbacks. Avoiding callbacks makes the code look cleaner. Callbacks generally represent the control flow mechanism. They only tell us how the program flows, not really what it does.

12. What is the output of the following code snippet?

setTimeout(() => {

  console.log('timer function completed');

}, 1000);
setImmediate(() => {

  console.log('immediate function completed');

});
for (let i = 0; i < 5; i++) {
  console.log(i);
}

 

Ans – Nodejs runs the fastest block of code before it goes to slower ones. Due to the async nature of nodejs, it will not wait for the timer to get over. It will also not wait for immediate function. It will run the loop first because it is the fastest. So, the output will be as follows:

0
1
2
3
4
Immediate function completed
Timer function completed

13. In which case await keyword does not work?

Ans – Await keyword works only when a promise is returned so if your code is not returning a promise, In that case, the await keyword will not work.

For eg: the Below code will not work

let response = await request(url)

For eg: the Below code will work

function makeRequest(url) {
  return new Promise(function (resolve, reject) {
    request(url, function (err, response, body) {
      if (!err && response.statusCode == 200) {
        resolve(body);
      } else {
        reject(err);
      }
    });
  });
}
async function main() {
  let response = await makeRequest(url);
  console.log(response);
}

14. What is Redis? 

Ans – Redis is a fast and efficient in-memory, key-value cache and store. The keys can contain strings, lists, sets, hashes, and other data structures. It reduces the response time by its intelligent caching.

15. What is JWT? How does JWT in Nodejs work?

Ans – JWT(JSON Web Token) is an encrypted token that is shared between the client and the server. 

 To authenticate a user, a client must send a JSON Web Token (JWT) in the header of an API to your backend. Once the token gets verified, the response is sent back to the client.

I was frequently asked these Nodejs interview questions in my recent interviews. I hope this helps you to crack Nodejs-related interviews. All the best. Please comment on the questions asked to you for helping others.

Also read:-

Commonly asked DBMS Interview Questions | 2022

What I did to become a software engineer?

 

Leave a Comment