preloader
NodeJS Interview Questions

Top Node.js Interview Question and Answers for Job Interview

author image

Preparing for an upcoming job interview in which Node JS is required then go through this page. It is good to brush up on your knowledge and skills and well prepare for your interview beforehand. Generally, there are a few questions are asked related to Node.js interview questions unless the interview revolves around node.js only. So we recommend you to prepare from Node.js interview questions and answer and focus on your interview.

About Node.js: It is a popularly known server-side platform that is an open-source, back-end JavaScript runtime environment that executes on the V8 engine and runs JavaScript code outside a web browser.

Also, prepare for TypeScript interview questions, Networking interview questions, and other language interview questions from here.

Node.js Interview Questions

1. Tell steps of “Control Flow” to control the functions calls?

2. Explain some timing features of Node.js?

3. Why do we need to use Node.js?

4. Tell some advantages of using promises than callbacks?

5. Explain fork in node JS?

6. Explain Node.js single-threaded?

7. Create a simple server in Node.js that brings back Hello World?

8. Explain different types of API functions of Node.js?

9. Explain REPL?

10. Tell two arguments that async.queue takes as input?

11. Explain the core purpose of module.exports?

12. Tools to use consistent code style?

13. Explain callback hell?

14. If Node.js is single-threaded then how it can handle concurrency?

15. Explain the use of async wait in node.js?

16. Explain node.js streams?

17. Explain node.js buffers?

18. Explain middleware?

19. Explain Reactor Pattern in Node.js?

20. Explain Event Emitter in Node.js?

21. Explain thread pool and library that handles it in Node.js

22. What is WASI and why is it being introduced?

23. How to calculate the duration of async operations?

24. How to calculate the performance of async operations?

25. Explain callback in Node.js.

26. Explain the term I/O?

27. Where do we use Node.js most frequently?

28. Explain NPM?

29. Explain the reasons why Node.js is chosen over other technologies like Java and PHP?

30. Name the database used with Node.js?

31. Name the common libraries used in Node.js?

32. Discuss the command required to import external libraries?

33. Explain the meaning of event-driven programming?

34. Explain Event Loop in Node.js?

35. Explain the Express.js package?

36. Tell us the way to implement async in Node.js?

37. Explain the control flow function?

38. Explain piping in Node.js?

39. Explain buffer class in Node.js?

40. Explain different types of HTTP requests?

41. Discuss first-class function in Javascript?

42. Explain Node.js and its works?

43. Tell us how Node.js overcomes the issue of blocking of I/O operations?

44. Explain the exit codes of Node.js?


Learn More Interview Questions Here:


Node.js Interview Questions For Fresher

1. Tell steps of “Control Flow” to control the functions calls?

  • Control the order of execution
  • Collect data
  • Limit concurrency
  • Call the following step in the program.

2. Explain some timing features of Node.js?

  • setTimeout/clearTimeout: It implement delays in code execution.
  • setInterval/clearInterval: It runs a code block multiple times.
  • setImmediate/clearImmediate: It set the execution of the code at the end of the event loop cycle.
  • process.nextTick: It set the execution of code at the beginning of the next event loop cycle.

3. Why do we need to use Node.js?

  • It makes building accessible network programs easy.
  • It is fast
  • It rarely blocks
  • It provides a unified programming language and data type
  • Everything in Node.js is asynchronous
  • Node.js yields great concurrency

4. Tell some advantages of using promises than callbacks?

The main benefit of using promise is you will get an object to choose the action that is required to be taken after the async task finishes. This provides more manageable code and avoids callback hell.

5. Explain fork in node JS?

It is used to spawn child processes. To make a new instance of v8 engine in node to run multiple workers.

6. Explain Node.js single-threaded?

Node.js was made just as an experiment in async processing. It is a new theory of undertaking async processing on one thread over the current thread-based implementation of scaling through different frameworks.

7. Create a simple server in Node.js that brings back Hello World?

var http = require(“http”);

http.createServer(function (request, response) {

response.writeHead(200, {‘Content-Type’: ‘text/plain’});

response.end(‘Hello World\n’);

}).listen(3000);

8. Explain different types of API functions of Node.js?

  • Asynchronous, non-blocking functions: In this API function I/O operations can be forked out from the main loop.
  • Synchronous, blocking functions: In this most of the operations influence the process that is running in the main loop

9. Explain REPL?

REPL means Read, Eval, Print, and Loop, which means evaluating the code on the go.

10. Tell two arguments that async.queue takes as input?

  • Task Function
  • Concurrency Value

Node.js Interview Questions And Answers

11. Explain the core purpose of module.exports?

module.exports are basically used to reveal functions of a specific module or file to be used somewhere else in the project. This can be used to capture all same functions in a file which further develops the project structure.

For example, let assume you have filed for all utils functions with util to acquire solutions in various programming languages of a problem statement.

const getSolutionInJavaScript = async ({

problem_id

}) => {

};

const getSolutionInPython = async ({

problem_id

}) => {

};

module.exports = { getSolutionInJavaScript, getSolutionInPython }

Thus using module.exports you are able to use these functions in some other file:

const { getSolutionInJavaScript, getSolutionInPython} = require("./utils”)

12. Tools to use consistent code style?

ESLint tools are used with any IDE to make sure a consistent coding style that maintains a codebase.

13. Explain callback hell?

async_A(function(){

async_B(function(){

async_C(function(){

async_D(function(){

….

});

});

});

});

In the above coding, we are passing callback functions that make the code unreadable and not able to maintain it, which leads to changing the async logic to avoid this.

14. If Node.js is single-threaded then how it can handle concurrency?

The Node.js main loop is single-threaded and all asynchronous calls are managed by libuv library.

For example:

const crypto = require(“crypto”);

const start = Date.now();

function logHashTime() {

crypto.pbkdf2(“a”, “b”, 100000, 512, “sha512”, () => {

console.log(“Hash: “, Date.now() - start);

});

}

logHashTime();

logHashTime();

logHashTime();

logHashTime();

This gives the output:

Hash: 1213

Hash: 1225

Hash: 1212

Hash: 1222

This is because libuv creates a thread pool to manage such concurrency.

15. Explain the use of async wait in node.js?

Here is how you can use async-await pattern:

// this code is to retry with exponential backoff

function wait (timeout) {

return new Promise((resolve) => {

setTimeout(() => {

resolve()

}, timeout);

});

}

async function requestWithRetry (url) {

const MAX_RETRIES = 10;

for (let i = 0; i <= MAX_RETRIES; i++) {

try {

return await request(url);

} catch (err) {

const timeout = Math.pow(2, i);

console.log(‘Waiting’, timeout, ‘ms’);

await wait(timeout);

console.log(‘Retrying’, err.message, i);

}

}

}

Follow Simple Steps to apply in these MNC’s:

16. Explain node.js streams?

In Node.js streams are occurrences of EventEmitter that is used to work with streaming data. It is used to handle and manipulate streaming large files (such as videos, mp3, etc.) over the network.

Different types of the stream are:

  • Writable: In these streams data can be written (for example, fs.createWriteStream()).
  • Readable: In these streams data can be read (for example, fs.createReadStream()).
  • Duplex: In these streams, data can be read and written (for example, net.Socket).
  • Transform: In this Duplex, streams can change or transform the data as it is written and read (for example, zlib.createDeflate()).

17. Explain node.js buffers?

Node.js buffers are temporary memory that streams use to hold on data until consumed. It is presented with extra use cases than JavaScript’s Unit8Array which is used to show a fixed-length sequence of bytes. This also allows legacy encodings like ASCII, utf-8, etc. It is a non-resizable (fixed) assigned memory outside the v8.

18. Explain middleware?

Middleware comes in the middle of request and business logic. It captures logs and allows rate limit, routing, authentication, and almost everything that is not a part of business logic. There are third-party middleware like body-parser and also write your own middleware for a particular use case.

19. Explain Reactor Pattern in Node.js?

It is a pattern for nonblocking I/O operations which is used in any event-driven architecture.

  • Reactor: Its dispatches the I/O event to suitable handlers
  • Handler: It executes those events

20. Explain Event Emitter in Node.js?

EventEmitter is a Node.js class that involves all the objects which are fully capable of emitting events. By using an eventEmitter.on() function you can attach the named events that are released by the object. So, whenever this object emits an event the attached functions are invoked synchronously.

const EventEmitter = require(‘events’);

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();

myEmitter.on(‘event’, () => {

console.log(‘an event occurred!');

});

myEmitter.emit(‘event’);

Node.js Interview Questions For 2 Year Experience

21. Explain thread pool and library that handles it in Node.js

The Thread pool is managed by the libuv library. libuv is a multi-function C library that gives support for async I/O-based operations like file systems, networking, and concurrency.

22. What is WASI and why is it being introduced?

WASI stands for WebAssembly System Interface is a Web assembly that provides an implementation of WebAssembly through WASI API in node.js executed using WASI class. The WASI was introduced to use the underlying operating system through a collection of POSIX-like functions which enables the application to use resources more effectively and features that need system-level access.

23. How to calculate the duration of async operations?

Performance API gives us with tools to measure performance metrics. Here are the examples of using async_hooks and perf_hooks

‘use strict’;

const async_hooks = require(‘async_hooks’);

const {

performance,

PerformanceObserver

} = require(‘perf_hooks’);

const set = new Set();

const hook = async_hooks.createHook({

init(id, type) {

if (type === ‘Timeout’) {

performance.mark(`Timeout-${id}-Init`);

set.add(id);

}

},

destroy(id) {

if (set.has(id)) {

set.delete(id);

performance.mark(`Timeout-${id}-Destroy`);

performance.measure(`Timeout-${id}`,

`Timeout-${id}-Init`,

`Timeout-${id}-Destroy`);

}

}

});

hook.enable();

const obs = new PerformanceObserver((list, observer) => {

console.log(list.getEntries()[0]);

performance.clearMarks();

observer.disconnect();

});

obs.observe({ entryTypes: [‘measure’], buffered: true });

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

This would give us the exact time it took to execute the callback.

24. How to calculate the performance of async operations?

Performance API gives us tools to calculate the performance metrics.

For Example:

const { PerformanceObserver, performance } = require(‘perf_hooks’);

const obs = new PerformanceObserver((items) => {

console.log(items.getEntries()[0].duration);

performance.clearMarks();

});

obs.observe({ entryTypes: [‘measure’] });

performance.measure(‘Start to Now’);

performance.mark(‘A’);

doSomeLongRunningProcess(() => {

performance.measure(‘A to Now’, ‘A’);

performance.mark(‘B’);

performance.measure(‘A to B’, ‘A’, ‘B’);

});

25. Explain callback in Node.js.

This function is called afterward a given task. In the meantime, it permits other codes to execute and prevents blocking. As an asynchronous platform, Node.js heavily depends on callback. All Node.js APIs are written to support callbacks.

26. Explain the term I/O?

It is used to explain any program, device, or operation that transfers data to or from a source and to or from another source. Every transfer is an outcome from one source and an input into another source. The medium/source can be a physical network, device, or file within a system

27. Where do we use Node.js most frequently?

  1. Real-time chats
  2. Internet of Things
  3. Complex SPAs (Single-Page Applications)
  4. Real-time collaboration tools
  5. Streaming applications
  6. Microservices architecture

28. Explain NPM?

NPM means Node Package Manager is totally responsible for handling all the packages and modules for Node.js.

Functionalities:

  • Provides online sources for node.js packages/modules, that is searchable on search.nodejs.org
  • It gives command-line utility to set up Node.js packages and also handles Node.js versions and dependencies.

29. Explain the reasons why Node.js is chosen over other technologies like Java and PHP?

  • Node.js is very fast than other
  • Node Package Manager (NPM) has more than 50,000 bundles available at the developer’s disposal
  • It is perfect for data-intensive, real-time web applications, as Node.js never postpones an API to return data
  • Better sync of code with server and client as they have the same code base
  • Node.js is a JavaScript library so it is easy for web developers to use.

30. Name the database used with Node.js?

MongoDB is the most used database with Node.js. It is a NoSQL, cross-platform, document-oriented database that gives a good performance, has high availability, and is very easy to scale.

Node.js Interview Questions For 5 Years Experience

31. Name the common libraries used in Node.js?

  • ExpressJS: It is a flexible Node.js web application framework that gives you a wide set of features to make web and mobile applications.
  • Mongoose: It is also a Node.js web application framework that easily connects an application to a database.

32. Discuss the command required to import external libraries?

For importing external libraries the “require” command is used. As an example - the “var http=require (“HTTP”)” command will load the HTTP library and exported object via HTTP variable.

var http = require(‘http’);

33. Explain the meaning of event-driven programming?

It uses the events to activate various functions. In here event can be anything, like pressing a key or mouse click, etc. A call-back function is pre-registered with the element performed whenever an event is triggered.

34. Explain Event Loop in Node.js?

Event loops manage async callbacks in Node.js. it is the most important environmental feature as it makes the foundation of the non-blocking input/output in Node.js.

35. Explain the Express.js package?

It is basically a flexible Node.js web application framework that gives an extensive set of features to develop web and mobile-based applications.

You may also prepare:

36. Tell us the way to implement async in Node.js?

In the given code you can see that the async code requests the JavaScript engine running the code to hold the request.get() function to finish before moving to the next line for execution.

async function fun1(req, res){

let response = await request.get(‘http://localhost:3000’);

if (response.err) {console.log(‘error’);}

else { console.log(‘fetched response’);

}

37. Explain the control flow function?

This function is a piece of code that executes in between several asynchronous function calls.

38. Explain piping in Node.js?

It is a mechanism used to link the output of one stream to another. To recover data from one stream and pass the outcome to another stream piping is used.

39. Explain buffer class in Node.js?

It stores raw data as same as in an array of integers but agrees to a raw memory distribution outside the V8 heap. Buffer class is used for the reason that pure JavaScript is not well-matched with binary data.

40. Explain different types of HTTP requests?

  • GET: it is used to recover the data
  • POST: It makes a change in reactions or state on the server
  • HEAD: Same as the GET method, but it asks for the reply without the response body
  • DELETE: It deletes the predetermined resource

41. Discuss first-class function in Javascript?

When functions can be treated like any other variable then those functions are first-class functions. There are different programming languages, like, scala, Haskell, etc. which follow first-class functions including JS. Now as a first-class function can be passed as a param to another function(callback) or a function can bring back another function(higher-order function). Some higher-order functions that are popularly used are map() and filter()

42. Explain Node.js and its works?

Node.js is a virtual machine that uses JavaScript as its scripting language and runs Chrome’s V8 JavaScript engine. Basically, Node.js is an event-driven architecture where I/O works async making it lightweight and more efficient. It is popularly used in creating desktop applications and a framework called electron that provides API to access OS-level features such as file system, network, etc.

43. Tell us how Node.js overcomes the issue of blocking of I/O operations?

As we know the node.js has an event loop that handles all the I/O operations in an async manner without blocking the main function.

44. Explain the exit codes of Node.js?

It tells us how a process got terminated or the motive behind the termination.

  • Uncaught fatal exception - (code - 1) - An exception that is not handled
  • Unused - (code - 2) – It reserved by bash
  • Fatal Error - (code - 5) - An error found in V8 with stderr output of the description
  • Internal Exception handler Run-time failure - (code - 7) - An exception while bootstrapping function is called
  • Internal JavaScript Evaluation Failure - (code - 4) - An exception when the bootstrapping process failed to bring back function value when evaluated.

I hope these Node.js interview questions will help you in your preparation for your upcoming Node.js technical interview. You can also prepare other coding language questions from this site.


Want to prepare for these languages:

Recent Articles