Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Explain the concept of stub in Node.js?

Answer»

Stubs are used in writing tests which are an important part of development. It replaces the whole function which is getting tested.  

This helps in scenarios where we need to test:

  • External calls which make tests slow and difficult to write (e.g HTTP calls/ DB calls)
  • Triggering different outcomes for a piece of code (e.g. what happens if an error is thrown/ if it passes)

For example, this is the function:

const request = require('request');const getPhotosByAlbumId = (id) => {const REQUESTURL = `https://jsonplaceholder.typicode.com/albums/${id}/photos?_limit=3`;return new Promise((resolve, reject) => { request.get(requestUrl, (ERR, res, body) => { if (err) { return reject(err); } resolve(JSON.parse(body)); });});};module.exports = getPhotosByAlbumId;To test this function this is the stubconst expect = require('chai').expect;const request = require('request');const sinon = require('sinon');const getPhotosByAlbumId = require('./index');describe('with Stub: getPhotosByAlbumId', () => {before(() => { sinon.stub(request, 'get') .yields(null, null, JSON.stringify([ { "albumId": 1, "id": 1, "title": "A real photo 1", "URL": "https://via.placeholder.com/600/92c952", "thumbnailUrl": "https://via.placeholder.com/150/92c952" }, { "albumId": 1, "id": 2, "title": "A real photo 2", "url": "https://via.placeholder.com/600/771796", "thumbnailUrl": "https://via.placeholder.com/150/771796" }, { "albumId": 1, "id": 3, "title": "A real photo 3", "url": "https://via.placeholder.com/600/24f355", "thumbnailUrl": "https://via.placeholder.com/150/24f355" } ]));});after(() => { request.get.restore();});it('should getPhotosByAlbumId', (done) => { getPhotosByAlbumId(1).then((photos) => { expect(photos.length).to.equal(3); photos.forEach(photo => { expect(photo).to.have.property('id'); expect(photo).to.have.property('title'); expect(photo).to.have.property('url'); }); done(); });});});
2.

Describe the exit codes of Node.js?

Answer»

Exit codes give us an idea of how a process got terminated/the REASON behind termination. 

A few of them are:

  • Uncaught fatal exception - (code - 1) - There has been an exception that is not handled
  • Unused - (code - 2) - This is reserved by bash
  • Fatal Error - (code - 5) - There has been an error in V8 with stderr output of the description
  • Internal Exception handler Run-time failure - (code - 7) - There has been an exception when BOOTSTRAPPING function was called
  • Internal JavaScript Evaluation Failure - (code - 4) - There has been an exception when the bootstrapping process FAILED to return function value when evaluated.
3.

For Node.js, why Google uses V8 engine?

Answer»

WELL, are there any other options available? Yes, of course, we have Spidermonkey from Firefox, Chakra from Edge but Google’s v8 is the most evolved(since it’s open-source so there’s a huge COMMUNITY helping in developing features and fixing BUGS) and fastest(since it’s written in c++) we got till now as a JavaScript and WebAssembly engine. And it is PORTABLE to almost every machine known.

4.

Why should you separate Express app and server?

Answer»

The server is responsible for initializing the routes, MIDDLEWARE, and other application LOGIC WHEREAS the app has all the business logic which will be served by the routes INITIATED by the server. This ensures that the business logic is encapsulated and decoupled from the application logic which makes the project more readable and MAINTAINABLE.

5.

Explain what a Reactor Pattern in Node.js?

Answer»

REACTOR pattern again a pattern for nonblocking I/O OPERATIONS. But in GENERAL, this is used in any event-driven architecture. 

There are two components in this: 1. Reactor 2. Handler.

Reactor: Its JOB is to dispatch the I/O event to APPROPRIATE handlers
Handler: Its job is to actually work on those events

6.

What is middleware?

Answer»

Middleware comes in between your request and business logic. It is MAINLY used to CAPTURE logs and ENABLE rate limit, routing, authentication, basically whatever that is not a PART of business logic. There are third-party middleware ALSO such as body-parser and you can write your own middleware for a specific use case.

7.

What are node.js buffers?

Answer»

In general, buffers is a temporary memory that is mainly used by STREAM to hold on to some data until consumed. Buffers are introduced with additional use CASES than JavaScript’s Unit8Array and are mainly used to represent a fixed-length sequence of bytes. This also supports LEGACY encodings LIKE ASCII, utf-8, etc. It is a fixed(non-resizable) allocated memory outside the v8.

8.

What is node.js streams?

Answer»

Streams are instances of EventEmitter which can be used to work with STREAMING data in Node.js. They can be used for handling and manipulating streaming large FILES(videos, mp3, etc) over the network. They use buffers as their temporary storage.

There are mainly FOUR types of the STREAM:

  • Writable: streams to which data can be written (for example, fs.createWriteStream()).
  • Readable: streams from which data can be read (for example, fs.createReadStream()).
  • DUPLEX: streams that are both Readable and Writable (for example, net.Socket).
  • Transform: Duplex streams that can modify or transform the data as it is written and read (for example, zlib.createDeflate()).
9.

How can we use async await in node.js?

Answer»

Here is an EXAMPLE of using async-await PATTERN:

// this code is to retry with exponential backofffunction 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);} }}
10.

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

Answer»

Since the node has an event loop that can be used to handle all the I/O operations in an ASYNCHRONOUS manner without blocking the main function. 

So for example, if some network call needs to happen it will be SCHEDULED in the event loop INSTEAD of the main thread(single thread). And if there are multiple such I/O calls each one will be queued accordingly to be executed separately(other than the main thread). 

THUS even though we have single-threaded JS, I/O ops are handled in a nonblocking way.

11.

Differentiate between process.nextTick() and setImmediate()?

Answer»

Both can be used to switch to an asynchronous mode of OPERATION by listener FUNCTIONS

process.nextTick() sets the callback to execute but setImmediate pushes the callback in the queue to be executed. So the event loop runs in the following manner

timers–>pending callbacks–>idle,prepare–>connections(poll,data,ETC)–>CHECK–>close callbacks

In this process.nextTick() method adds the callback function to the START of the next event queue and setImmediate() method to place the function in the check phase of the next event queue.

12.

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

Answer»

The main loop is single-threaded and all async 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: 1213Hash: 1225Hash: 1212Hash: 1222

This is because libuv sets up a thread pool to HANDLE such concurrency. How MANY threads will be there in the thread pool depends upon the number of cores but you can override this.

13.

What is an event-loop in Node JS?

Answer»

Whatever that is async is managed by event-loop using a queue and listener.  We can GET the idea using the following diagram:

Node.js Event Loop

So when an async function needs to be executed(or I/O) the main THREAD SENDS it to a different thread allowing v8 to keep executing the main code. Event loop involves different phases with specific tasks such as timers, pending callbacks, idle or prepare, poll, check, close callbacks with different FIFO QUEUES. ALSO in between iterations it checks for async I/O or timers and shuts down cleanly if there aren't any.

14.

What do you understand by callback hell?

Answer»

async_A(function(){ async_B(function(){ async_C(function(){ async_D(function(){ .... }); }); });});

For the above example, we are passing CALLBACK functions and it makes the code UNREADABLE and not maintainable, THUS we should change the async logic to avoid this.