Node - Js Interview Questions: Premise
Node - Js Interview Questions: Premise
Node - Js Interview Questions: Premise
Premise
This was said back in 2007, and we can say that it is proving true till now. You can think of any
technical keyword and there might be a JavaScript library build around it. So if it’s so popular and
in demand, this can be a great programming language to learn. But that’s not the only skill that
is required, since you have to apply this to solve practical problems. And one of such problems is
to build scalable products.
Gen Z backend
After jQuery animation dev shifted to a single page application for better control of ui/ux and thus
came frontend frameworks such as angular js and angular. After that JavaScript was made
available to port into literally any modern machine that exists and runs as a standalone
application i.e Node.js. It was widely accepted as a backend framework and comes to the top,
2nd year in a row in 2020 of StackOverflow survey.
As developers are busy getting an experience in node.js it’s nice to have a curated list of
Node.js interview questions to revise. Also, to further consolidate your knowledge on
Javascript, refer to this source.
When functions can be treated like any other variable then those functions are first-class
functions. There are many other programming languages, for example, scala, Haskell, etc which
follow this including JS. Now because of this function can be passed as a param to another
function(callback) or a function can return another function(higher-order function). map() and
filter() are higher-order functions that are popularly used.
Node.js is a virtual machine that uses JavaScript as its scripting language and runs Chrome’s V8
JavaScript engine. Basically, Node.js is based on an event-driven architecture where I/O runs
asynchronously making it lightweight and efficient. It is being used in developing desktop
applications as well with a popular framework called electron as it provides API to access OS-level
features such as file system, network, etc.
Get Ready with Free Mock Coding Interview
3. How do you manage packages in your node.js project?
It can be managed by a number of package installers and their configuration file accordingly. Out
of them mostly use npm or yarn. Both provide almost all libraries of javascript with extended
features of controlling environment-specific configurations. To maintain versions of libs being
installed in a project we use package.json and package-lock.json so that there is no issue in
porting that app to a different environment.
Node.js provides simplicity in development because of its non-blocking I/O and even-based
model results in short response time and concurrent processing, unlike other frameworks
where developers have to use thread management.
It runs on a chrome v8 engine which is written in c++ and is highly performant with constant
improvement.
Also since we will use Javascript in both the frontend and backend the development will be
much faster.
And at last, there are ample libraries so that we don’t need to reinvent the wheel.
5. Explain the steps how “Control Flow” controls the functions calls?
A fork in general is used to spawn child processes. In node it is used to create a new instance of
v8 engine to run multiple workers to execute the code.
Node.js was created explicitly as an experiment in async processing. This was to try a new theory
of doing async processing on a single thread over the existing thread-based implementation of
scaling via different frameworks.
10. How do you create a simple server in Node.js that returns Hello
World?
Asynchronous, non-blocking functions - mostly I/O operations which can be fork out of
the main loop.
Synchronous, blocking functions - mostly operations that influence the process running
in the main loop.
PL in Node.js stands for Read, Eval, Print, and Loop, which further means evaluating code on the
go.
13. List down the two arguments that async.queue takes as input?
Task Function
Concurrency Value
Get Ready with Free Mock Coding Interview
14. What is the purpose of module.exports?
This is used to expose functions of a particular module or file to be used elsewhere in the project.
This can be used to encapsulate all similar functions in a file which further improves the project
structure.
For example, you have a file for all utils functions with util to get solutions in a different
programming language of a problem statement.
Thus using module.exports we can use these functions in some other file:
ESLint can be used with any IDE to ensure a consistent coding style which further helps in
maintaining the codebase.
async_A(function(){
async_B(function(){
async_C(function(){
async_D(function(){
....
});
});
});
});
Get Ready with Free Mock Coding Interview
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.
Whatever that is async is managed by event-loop using a queue and listener. We can get the
idea using the following diagram:
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.
The main loop is single-threaded and all async calls are managed by libuv library.
For example:
Hash: 1213
Hash: 1225
Hash: 1212
Hash: 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.
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.
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.
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.
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.
Get Ready with Free Mock Coding Interview
24. What is middleware?
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.
Reactor pattern again a pattern for nonblocking I/O operations. But in general, this is used in any
event-driven architecture.
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.
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.
Exit codes give us an idea of how a process got terminated/the reason behind termination.
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 Get Ready with Free Mock Coding Interview
Internal JavaScript Evaluation Failure - (code - 4) - There has been an exception when the
bootstrapping process failed to return function value when evaluated.
Stubs are used in writing tests which are an important part of development. It replaces the whole
function which is getting tested.
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)
EventEmitter is a Node.js class that includes all the objects that are basically capable of emitting
events. This can be done by attaching named events that are emitted by the object using an
eventEmitter.on() function. Thus whenever this object throws an even the attached functions are
invoked synchronously. Get Ready with Free Mock Coding Interview
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 applications run on a single processor, which means that by default they don’t take
advantage of a multiple-core system. Cluster mode is used to start up multiple node.js processes
thereby having multiple instances of the event loop. When we start using cluster in a nodejs app
behind the scene multiple node.js processes are created but there is also a parent process called
the cluster manager which is responsible for monitoring the health of the individual instances
of our application.
Clustering in Node.js
The Thread pool is handled by the libuv library. libuv is a multi-platform C library that provides
support for asynchronous I/O-based operations such as file systems, networking, and
concurrency.
Cluster:
Worker threads:
Performance API provides us with tools to figure out the necessary performance metrics. A simple
example would be 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.
https://www.interviewbit.com/nodejs-mcq/
https://www.interviewbit.com/blog/node-js-projects/
https://www.interviewbit.com/blog/node-js-vs-react-js/
https://www.interviewbit.com/blog/node-js-vs-django/
var fs = require("fs");
var fs = import("fs");
package fs;
import fs;
New Package Manager Get Ready with Free Mock Coding Interview
Node Package Manager
True
False
module.expose
module.spread
module.export
Duplex
Readable
Writable
Global
Local
Public
Private
Get Ready with Free Mock Coding Interview
7. Which module is used to serve static files in Node.js?
static
node-static
http
node-http
18
20
22
24
==
===
isEqual()
isEqualNode()
FAQ Contact Us
Interview Preparation
View All
Top Articles
10 Best Data Structures And Algorithms Books Exciting C Projects Ideas With Source Code
Top MCQ