Top Node.js Interview Questions & Answers (2021)

Node.js Interview Questions
0

Node.js is a JavaScript runtime environment which is lightweight and has shorter response cycles. It is asynchronous, event-driven, and runs on Chrome’s V8 JavaScript engine. It works on a single-threaded and non-blocking programming technique where if there is no work to be executed then Node.js will sleep. This results in memory efficiency, fast speed, and scalability as some of the prominent features of the Node.js applications.  

Node.js vs traditional web-serving techniques
Image credit: Toptal.com

In traditional web-serving techniques, each connection starts a new thread using up RAM and other resources. In contrast to this, Node.js works on a single thread technique using non-blocking I/O calls. Therefore many connections can be supported using the event-based callback on a single thread. 

Applications which are best suited for Node.js are real-time applications such as chat application, API, data streaming app, application monitoring dashboard, stock trader’s dashboard, etc. To read about the scenarios where we can use Node.js in more detail see here. 

Basic Interview Questions on Node.js

1. What are the benefits of Node.js? 

  • Simple:  It works on single thread architecture, non-blocking I/O, and event-based models. Therefore, it is easier to manage and code, unlike the multi-threaded web-serving techniques. 
  • Fast: It uses JavaScript for creating the backend and frontend of an application, hence it is faster. 
  • Performance: It is supported by Chrome’s V8 JavaScript engine, which in turn is written in C++. Therefore the performance of Node.js is better and provides scalability, especially for real-time applications. 
  • Response time: It drastically reduces the response time for applications. 
  • Libraries: Node.js comes with a huge set of library functions, therefore we need not code for all those functions again. 
  • Cross-platform applications: It supports the creation of cross-platform applications. 
  • Community support: Like other open-source technologies, Node.js is also backed by strong community support which eases the development process. 

2. Mention the differences between Node.js and AngularJS? 

Node.js  AngularJS 
It is a run-time environment.  It is a web application development framework. 
Needs installation on the computer before use.  Does not need an installation before use, we just need to add the file to the application. 
Written in C, C++, and JavaScript.  Written in JavaScript only. 
Mostly used to create fast and real-time server-side networking applications.  Mostly used to create single-page client-side web applications. 

 

3. Which API functions are available in Node.js? 

Node.js has two types of API functions: 

  • Non-blocking/ asynchronous API functions– They operate asynchronously, which means when a request is made for data, it will not be blocked till the data is received. Example: email 
  • Blocking/ synchronous API functions– They operate synchronously, which means when a request is made for data, it will be blocked till the data is received. Example: Video meetings 

4. What do you understand by event-driven programming in Node.js? 

Event-driven programming uses various events(mouse click, keypress, messages from other programs) to initiate/trigger a function in the program. Callback functions are already registered with events and when an event is executed, the corresponding callback function is called. Therefore the flow of the program is decided by these events and hence the name.  

5. Explain the architecture of a Node.js web application. 

Node.js application architecture
Image credit: Andranik Keshishyan 
  • Application:  It has the code, built-in functions, modules written in JavaScript. 
  • V8 server: Node.js is built on top of the V8 JavaScript server which compiles the application’s JavaScript into machine language and therefore is super fast. 
  • Node API bindings: It is a wrapper around a library to communicate with the code written in other languages. 
  • libuv: It is written in C and handles asynchronous I/O synch as asynchronous TCP/UDP sockets, event loop, DNS resolution, and file read/write, etc. 
  • Event queue: All the events written in the code are registered with Node.js. When an event is triggered, it is queued in the ‘event queue’. 
  • Event loop:  It picks up the events from the event queue and calls their callback functions. The code runs in the event loop, which handles all asynchronous calls. The event loop is handled via libuv. 
  • Worker threads: The event loop sends the events to worker threads for actual processing after calling the callback functions.

6. What do you understand by REPL in Node.js? 

Read-Eval-Print-Loop (REPL) is an interactive shell or a programming language environment (console) in Node.js. It takes user input as a single expression and then provides output back to the console. It is used to check the JavaScript or Node.js code quickly on the console. 

 It comes bundled with the Node.js installation and has four tasks : 

  • Read: Shell reads the expressions which user enters and parses them into the data structure 
  • Evaluate (Eval): Evaluates the data structure 
  • Print: Prints the result on the console 
  • Loop: Loops the operations till the user quits 

To launch REPL in Linux/Unix or Windows, go to the command prompt and then write ‘node’. Note: To exit from REPL press Ctrl+C  twice or .exit then ‘Enter’ key. 

Intermediate Interview Questions on Node.js 

1. What is an error-first callback in Node.js? 

It is a function in Node.js which has two types of arguments- error or successful response data: 

  • The first argument is reserved for an error object. If there is an error during function execution then the error is returned through the error object. 
  • Subsequent arguments are for data which returns a response. If there is no error then the error object will be set to NULL. 

Example: 

 fs.readFile('my_text_file.txt', function(err, data) { 

// If an error occurred, handle it (throw error) 

if (err) { 

console.log('Error Found:' + err); 

throw err; 

} 

// Otherwise, log the data 

console.log(data); 

});

2. Why do we use module.exports in Node.js? 

The ‘module.exports’ are properties of the ‘module’ object which are included in every JavaScript file of Node.js by default. They are used to export any literal/ function/ object /primitive values as a module. We can export any value/ function/ object by including them as a property of the ‘module.exports’ object. 

Syntax: 

module.exports = literal | function | object

3. What is a URL module in Node.js? 

It is used to split the web address into smaller and readable parts. Therefore helps users to understand these readable parts of the web address. URL is a built-in module hence it can be imported in the JavaScript file by using the ‘require()’ method as below: 

var url = require('url');

To split the URL, the ‘parse()’ method is used, this method returns a URL module. The split chunks of address are present as properties of this URL module. 

Example: 

var url = require('url'); 
var adr = 'http://localhost:8080/default.htm?year=2017&month=february'; 
var q = url.parse(adr, true); 

console.log(q.host); //returns 'localhost:8080' 
console.log(q.pathname); //returns '/default.htm' 
console.log(q.search); //returns '?year=2017&month=february' 

var qdata = q.query; //returns an object: { year: 2017, month: 'february' } 
console.log(qdata.month); //returns 'february'

4. Explain the differences between spawn() and fork() methods in Node.js. 

spawn()  fork() 
Spawns a new process using the command and command-line arguments.  It is a special instance of spawn used by parent and child processes to communicate through send() function. 
No new V8 instance is created.  Runs a new instance of V8. 
Used to run system commands.  Used to create multiple workers. 
Syntax: 

 child_process.spawn(command[, args][, options]) 

Syntax: 

child_process.fork(modulePath[, args][, options]) 

 5. If Node.js is single-threaded then how does it handle concurrency? 

Node.js uses an event loop and libuv library to handle concurrency. The single and primary thread executes the program code which is a single thread however the event loop creates multiple threads for asynchronous tasks. The asynchronous tasks like database reading or I/O operations are handled by the libuv library via other threads. Hence asynchronous tasks do not block the main thread and the ‘event queue’ helps to attain concurrency. 

6. How does Node.js overcome the problem of blocking I/O operations? 

Node.js uses an event-based model to overcome the problem of blocking I/O operations. The event loop handles asynchronous operations like I/O without blocking the main thread.  I/O operations are handled separately from the main thread via event loop and event queue as shown below. 

Non-blocking I/O in Node.js
Image credit: monocubed.com

Advanced Interview Questions on Node.js 

1. How are worker threads different from clusters? 

Worker Threads 

  • There is one process with multiple threads where each thread has one node instance. 
  • It shares memory with other threads. 
  • Used for CPU-intensive tasks such as file operations. 

Cluster: 

  • There is one process on each CPU with an Inter-Process Communication(IPC) for communication. 
  • HTTP requests on a single port from multiple servers can be executed using a cluster. 
  • For each process, there are separate memory and node instances giving rise to memory issues. 

2. Explain the different timing features provided by Node.js. 

Node.js provides the Timers module to execute code after a set period. This module contains various functions for this purpose, they are: 

  • setTimeout/clearTimeout: Introduce delays in code execution. 
  • setImmediate/clearImmediate: Sets the code execution at the end of the event-loop cycle. 
  • setInterval/clearInterval: Runs a code block multiple times. 
  • process.nextTick: Sets the code execution at the beginning of the next event-loop cycle. 

Read about timing features in detail here. 

3. Which exit codes can be used in Node.js? 

Exit codes are specific codes which are generated after a process gets terminated. These exit codes provide the reason behind the process termination. Most popular of them as given below: 

  • Code 1 (Uncaught fatal exception): Unhandled exception 
  • Code 2(Unused): Reserved by Bash 
  • Code 4(Internal JavaScript Evaluation Failure): Exception when the bootstrapping process failed to return function 
  • Code 5(Fatal error): Error in V8 on stderr 
  • Code 7(Internal Exception handler Run-time failure): Exception while calling bootstrapping function 

 4. What are the different streams present in Node.js? 

Streams are objects which are used for streaming large data files continuously. These objects are used to read and write huge data files using buffers as temporary data storage. There are four types of streams in Node.js: 

  • Readable: Data can be read from these streams. E.g., fs.createReadStream() 
  • Writable: Data can be written to these streams. E.g., fs.createWriteStream() 
  • Duplex: Support both reads and write. E.g., net.Socket 
  • Transform: They are duplex streams which can modify the data while reading or writing. E.g., zlib.createDeflate() 

5. How do you decide if Node.js is suitable for building a particular type of application? 

Node.js is suitable for the application requiring real-time interactions and data exchange. 

Few popular application examples where Node.js is helpful are: 

  • Chat/messaging applications 
  • Streaming application 
  • E-commerce applications 
  • Microservices 
  • API 

You may read in detail about this here. 

6. How to measure the performance of async operations? 

The performance API provides us ways to measure the performance of async operations. 

Node.js supports the following Performance APIs: 

  • High-Resolution Time 
  • Performance Timeline 
  • User Timing 
Example: 

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

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

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

  performance.clearMarks(); 

}); 

obs.observe({ type: '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'); 

});

 

 

 

0

Related Articles

Responses