NODEJS
NODEJS
x )
[Link]/nodejs-interview-questions/
Star Notifications
[Link] 1/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
[Link] APIs
[Link] Coding Practice
[Link] Commands
Table of Contents
Introduction
[Link] Setup
[Link] Data Types
[Link] Architecture
[Link] Events
[Link] File System
[Link] Streams
[Link] Multithreading
[Link] Web Module
[Link] Middleware
[Link] RESTFul API
[Link] Routing
[Link] Caching
[Link] Error Handling
[Link] Logging
[Link] Internationalization
[Link] Testing
[Link] Miscellaneous
# 1. INTRODUCTION
Q. What is [Link]?
[Link] is an open-source server side runtime environment built on Chrome's V8 JavaScript engine. It provides an event driven, non-blocking
(asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.
↥ back to top
All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed
asynchronously
README for a particular request. So, this single thread doesn't have to wait for the request to complete and is free to handle the next
request. When asynchronous I/O work completes then it processes the request further and sends the response.
↥ back to top
[Link] 2/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Fast in Code execution – [Link] uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper
over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within [Link] also become
faster.
Single Threaded but Highly Scalable – [Link] uses a single thread model for event looping. The response from these events may or may
not reach the server immediately. However, this does not block other operations. Thus making [Link] highly scalable. Traditional servers
create limited threads to handle requests while [Link] creates a single thread that provides service to much larger numbers of such
requests.
[Link] library uses JavaScript – This is another important aspect of [Link] from the developer's point of view. The majority of
developers are already well-versed in JavaScript. Hence, development in [Link] becomes easier for a developer who knows JavaScript.
There is an Active and vibrant community for the [Link] framework – The active community always keeps the framework updated with
the latest trends in the web development.
No Buffering – [Link] applications never buffer any data. They simply output the data in chunks.
↥ back to top
[Link] works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel. An Event Loop is
a functionality which handles and processes all your external events and just converts them to a callback function. It invokes all the event
handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request
doesn't have to wait if the processing is not complete.
While processing a request, [Link] attaches a callback function to it and moves it to the back-end. Now, whenever its response is ready, an
event is called which triggers the associated callback function to send this response.
↥ back to top
# 2. [Link] SETUP
mkdir myapp
cd myapp
npm init
This creates a [Link] file in your myapp folder. The file contains references for all npm packages you have downloaded to your project.
The command will prompt you to enter a number of things. You can enter your way through all of them EXCEPT this one:
[Link]
[Link] 3/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
/**
* [Link]
*/
const express = require('express');
const app = express();
[Link](3000, function () {
[Link]('App listening on port 3000!');
});
node [Link]
Example:
/**
* URL Module in [Link]
*/
const url = require('url');
const adr = '[Link]
const q = [Link](adr, true);
[Link]([Link]); // localhost:8080
[Link]([Link]); // "/[Link]"
[Link]([Link]); // "?year=2022&month=september"
↥ back to top
Just like JS, there are two categories of data types in Node: Primitives and Objects.
1. Primitives:
String
Number
BigInt
[Link] 4/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Boolean
Undefined
Null
Symbol
2. Objects:
Function
Array
Buffer
↥ back to top
String functions:
Function Description
indexOf() It is useful to get the index of a specified character or a part of the string.
Join() It is useful to join the array of strings and those are separated by comma (,) operator.
Example:
/**
* String Data Type
*/
const str1 = "Hello";
const str2 = 'World';
↥ back to top
Example:
/**
* Number Data Type
*/
// Example 01:
const num1 = 10;
const num2 = 20;
// Example 02:
[Link](parseInt("32")); // 32
[Link](parseFloat("8.24")); // 8.24
[Link] 5/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
[Link](parseInt("234.12345")); // 234
[Link](parseFloat("10")); // 10
// Example 03:
[Link](isFinite(10/5)); // true
[Link](isFinite(10/0)); // false
// Example 04:
[Link](5 / 0); // Infinity
[Link](-5 / 0); // -Infinity
↥ back to top
Example:
/**
* BigInt Data Type
*/
const maxSafeInteger = 99n; // This is a BigInt
const num2 = BigInt('99'); // This is equivalent
const num3 = BigInt(99); // Also works
↥ back to top
The boolean() function is used to convert any data type to a boolean value. According to the rules, false, 0, NaN, null, undefined, empty string
evaluate to false and other values evaluates to true.
Example:
/**
* Boolean Data Type
*/
// Example 01:
const isValid = true;
[Link](isValid); // true
// Example 02:
[Link](true && true); // true
[Link](true && false); // false
[Link](true || false); // true
[Link](false || false); // false
[Link](!true); // false
[Link](!false); // true
↥ back to top
In [Link], if a variable is defined without assigning any value, then that will take undefined as value. If we assign a null value to the variable,
then the value of the variable becomes null.
Example:
[Link] 6/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
/**
* NULL and UNDEFINED Data Type
*/
let x;
[Link](x); // undefined
let y = null;
[Link](y); // null
↥ back to top
Example:
/**
* Symbol Data Type
*/
const NAME = Symbol()
const person = {
[NAME]: 'Ritika Bhavsar'
}
↥ back to top
Example:
/**
* Function in [Link]
*/
function Messsage(name) {
[Link]("Hello "+name);
}
↥ back to top
Example:
/**
* Buffer Data Type
*/
let b = new Buffer(10000);
let str = "----------";
[Link](str);
[Link] 7/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
[Link]( [Link] ); // 10
[Link]( [Link] ); // 10000
↥ back to top
# 4. [Link] ARCHITECTURE
A new request coming in is one kind of event. The server starts processing it and when there is a blocking IO operation, it does not wait until it
completes and instead registers a callback function. The server then immediately starts to process another event ( maybe another request ).
When the IO operation is finished, that is another kind of event, and the server will process it ( i.e. continue working on the request ) by
executing the callback as soon as it has time.
[Link] Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model.
[Link] Processing model mainly based on Javascript Event based model with Javascript callback mechanism.
↥ back to top
[Link] 8/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Syntax:
Example:
The following table lists some of the important core modules in [Link].
http http module includes classes, methods and events to create [Link] http server.
url url module includes methods for URL resolution and parsing.
fs fs module includes classes, methods, and events to work with file I/O.
↥ back to top
1. Blocking I/O: Application will make a function call and pause its execution at a point until the data is received. It is called as "Synchronous".
2. Non-Blocking I/O: Application will make a function call, and, without waiting for the results it continues its execution. It is called as
"Asynchronous".
[Link] 9/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
1. Resources: They are shared by multiple applications for I/O operations, generally slower in executions.
2. Synchronous Event De-multiplexer/Event Notifier: This uses Event Loop for blocking on all resources. When a set of I/O operations
completes, the Event De-multiplexer pushes the new events into the Event Queue.
3. Event Loop and Event Queue: Event Queue queues up the new events that occurred along with its event-handler, pair.
4. Request Handler/Application: This is, generally, the application that provides the handler to be executed for registered events on resources.
↥ back to top
These objects are modules, functions, strings and object itself as explained below.
1. global:
It is a global namespace. Defining a variable within this namespace makes it globally accessible.
var myvar;
2. process:
It is an inbuilt global object that is an instance of EventEmitter used to get information on current process. It can also be accessed using
require() explicitly.
3. console:
function printHello() {
[Link]( "Hello, World!");
}
[Link] 10/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
// Now call above function after 2 seconds
var timeoutObj = setTimeout(printHello, 2000);
5. __dirname:
It is a string. It specifies the name of the directory that currently contains the code.
[Link](__dirname);
6. __filename:
It specifies the filename of the code being executed. This is the resolved absolute path of this code file. The value inside a module is the path to
that module file.
[Link](__filename);
↥ back to top
V8 is a C++ based open-source JavaScript engine developed by Google. It was originally designed for Google Chrome and Chromium-based
browsers ( such as Brave ) in 2008, but it was later utilized to create [Link] for server-side coding.
V8 is the JavaScript engine i.e. it parses and executes JavaScript code. The DOM, and the other Web Platform APIs ( they all makeup runtime
environment ) are provided by the browser.
V8 is known to be a JavaScript engine because it takes JavaScript code and executes it while browsing in Chrome. It provides a runtime
environment for the execution of JavaScript code. The best part is that the JavaScript engine is completely independent of the browser in which
it runs.
↥ back to top
It allows the CPU and other resources to be used simultaneously while still performing I/O operations, thereby resulting in efficient use of
resources and network.
It facilitates an event-driven approach wherein I/O and other activities are performed using callback-based notifications.
It provides mechanisms to handle file system, DNS, network, child processes, pipes, signal handling, polling and streaming
It also includes a thread pool for offloading work for some things that can't be done asynchronously at the operating system level.
↥ back to top
Using an Interpreter: The interpreter scans the code line by line and converts it into byte code.
Using a Compiler: The Compiler scans the entire document and compiles it into highly optimized byte code.
The V8 engine uses both a compiler and an interpreter and follows just-in-time (JIT) compilation to speed up the execution. JIT compiling
works by compiling small portions of code that are just about to be executed. This prevents long compilation time and the code being
compiles is only that which is highly likely to run.
↥ back to top
# 5. [Link] EVENTS
[Link] 11/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
EventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node's built-in modules inherit from EventEmitter
including prominent frameworks like [Link]. An emitter object basically has two main features:
Example 01: Create an event emitter instance and register a couple of callbacks
/**
* Callbacks Events
*/
const events = require('events');
const eventEmitter = new [Link]();
function listenerOne() {
[Link]('First Listener Executed');
}
function listenerTwo() {
[Link]('Second Listener Executed');
}
// When the event "listenerOne" is emitted, both the above callbacks should be invoked.
[Link]('listenerOne');
// Output
First Listener Executed
Second Listener Executed
Example 02: Registering for the event to be fired only one time using once.
/**
* Emit Events Once
*/
const events = require('events');
const eventEmitter = new [Link]();
function listenerOnce() {
[Link]('listenerOnce fired once');
}
// Output
listenerOnce fired once
/**
* Callback Events with Parameters
*/
const events = require('events');
const eventEmitter = new [Link]();
[Link] 12/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
[Link]('status', 200, 'ok');
// Output
status 200 and ok
↥ back to top
[Link] is a single-threaded application, but it can support concurrency via the concept of event and callbacks. Every API of [Link] is
asynchronous and being single-threaded, they use async function calls to maintain concurrency. Node uses observer pattern. Node thread
keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute.
Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks.
The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.
The event loop allows us to use callbacks and promises.
The event loop executes the tasks starting from the oldest first.
Example:
/**
* Event loop in [Link]
*/
const events = require('events');
const eventEmitter = new [Link]();
// Output
[Link] 13/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Connection succesful.
Data received succesfully.
Program Ended.
↥ back to top
The [Link]() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program
[Link]() method is called for the first time before the event loop is processed.
2. setImmdeiate():
The setImmediate() method is used to execute a function right after the current event loop finishes. It is callback function is placed in the check
phase of the next event queue.
Example:
/**
* setImmediate() and [Link]()
*/
setImmediate(() => {
[Link]("1st Immediate");
});
setImmediate(() => {
[Link]("2nd Immediate");
});
[Link](() => {
[Link]("1st Process");
});
[Link](() => {
[Link]("2nd Process");
});
// Output
Program Started
1st Process
2nd Process
1st Immediate
2nd Immediate
↥ back to top
Callback is called when task get completed and is asynchronous equivalent for a function. Using Callback concept, [Link] can process a large
number of requests without waiting for any function to return the result which makes [Link] highly scalable.
Example:
/**
* Callback Function
*/
function myAsync(a, b, callback) {
setTimeout(function () {
callback(a + b);
[Link] 14/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
}, 100);
}
[Link]("Before Asynchronous Call");
// Output
Before Asynchronous Call
After Asynchronous Call
Sum: 30
↥ back to top
[Link] events module which emits named events that can cause corresponding functions or callbacks to be called. Functions ( callbacks )
listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in
order to which they were registered.
All objects that emit events are instances of the EventEmitter class. The event can be emitted or listen to an event with the help of EventEmitter
Example:
/**
* Events Module
*/
const event = require('events');
const eventEmitter = new [Link]();
// call event
[Link]('Sum', 10, 20);
// Output
Total: 30
2. Callbacks:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete
some kind of routine or action.
Example:
/**
* Callbacks
*/
function sum(number) {
[Link]('Total: ' + number);
}
[Link] 15/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
// Output
Total: 30
Callback functions are called when an asynchronous function returns its result, whereas event handling works on the observer pattern. The
functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. [Link] has multiple in-built
events available through events module and EventEmitter class which are used to bind events and event-listeners
↥ back to top
The pattern used across all the asynchronous methods in [Link] is called Error-first Callback. Here is an example:
Any asynchronous method expects one of the arguments to be a callback. The full callback argument list depends on the caller method, but the
first argument is always an error object or null. When we go for the asynchronous method, an exception thrown during function execution
cannot be detected in a try/catch statement. The event happens after the JavaScript engine leaves the try block.
In the preceding example, if any exception is thrown during the reading of the file, it lands on the callback function as the first and mandatory
parameter.
↥ back to top
An asynchronous function is one where some external activity must complete before a result can be processed; it is "asynchronous" in the
sense that there is an unpredictable amount of time before a result becomes available. Such functions require a callback function to handle
errors and process the result.
Example:
/**
* Callback Hell
*/
getData(function(a){
getMoreData(a, function(b){
getMoreData(b, function(c){
getMoreData(c, function(d){
getMoreData(d, function(e){
...
});
});
});
});
});
↥ back to top
[Link] 16/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Async is a really powerful npm module for managing asynchronous nature of JavaScript. Along with [Link], it also works for JavaScript
written for browsers.
Async provides lots of powerful utilities to work with asynchronous processes under different scenarios.
Promises are alternative to callbacks while dealing with asynchronous code. Promises return the value of the result or an error exception. The
core of the promises is the .then() function, which waits for the promise object to be returned.
The .then() function takes two optional functions as arguments and depending on the state of the promise only one will ever be called. The
first function is called when the promise if fulfilled (A successful result). The second function is called when the promise is rejected.
Example:
/**
* Promises
*/
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Successful!");
}, 300);
});
Async await makes asynchronous code look like it's synchronous. This has only been possible because of the reintroduction of promises into
[Link]. Async-Await only works with functions that return a promise.
Example:
/**
* Async Await
*/
const getrandomnumber = function(){
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve([Link]([Link]() * 20));
}, 1000);
});
}
addRandomNumber();
↥ back to top
Example:
/**
* Callback Handler
*/
const Division = (numerator, denominator, callback) => {
if (denominator === 0) {
[Link] 17/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
callback(new Error('Divide by zero error!'));
} else {
callback(null, numerator / denominator);
}
};
// Function Call
Division(5, 0, (err, result) => {
if (err) {
return [Link]([Link]);
}
[Link](`Result: ${result}`);
});
↥ back to top
1. setTimeout():
This function schedules code execution after the assigned amount of time ( in milliseconds ). Only after the timeout has occurred, the code will
be executed. This method returns an ID that can be used in clearTimeout() method.
Syntax:
Example:
function printMessage(arg) {
[Link](`${arg}`);
}
2. setImmediate():
The setImmediate() method executes the code at the end of the current event loop cycle. The function passed in the setImmediate() argument
is a function that will be executed in the next iteration of the event loop.
Syntax:
setImmediate(callback, args)
Example:
// Output
[Link] 18/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
// Normal statement in the event loop
// setImmediate() function running...
// setTimeout() function running...
3. setInterval():
The setInterval() method executes the code after the specified interval. The function is executed multiple times after the interval has passed. The
function will keep on calling until the process is stopped externally or using code after specified time period. The clearInterval() method can be
used to prevent the function from running.
Syntax:
Example:
setInterval(function() {
[Link]('Display this Message intervals of 1 seconds!');
}, 1000);
↥ back to top
The "normal" way in [Link] is probably to read in the content of a file in a non-blocking, asynchronous way. That is, to tell Node to read in the
file, and then to get a callback when the file-reading has been finished. That would allow us to hand several requests in parallel.
Read files
Create files
Update files
Delete files
Rename files
Read Files
[Link]
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
/**
* read_file.js
*/
const http = require('http');
const fs = require('fs');
[Link](function (req, res) {
[Link]('[Link]', function(err, data) {
[Link](200, {'Content-Type': 'text/html'});
[Link](data);
[Link]();
});
}).listen(8080);
[Link] 19/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Initiate read_file.js:
node read_file.js
↥ back to top
# 7. [Link] STREAMS
Each type of Stream is an EventEmitter instance and throws several events at different instance of times.
Example:
const fs = require("fs");
const data = '';
[Link]('end',function() {
[Link](data);
});
[Link]('error', function(err) {
[Link]([Link]);
});
[Link]("Program Ended");
Writing to a Stream:
const fs = require("fs");
const data = 'Simply Easy Learning';
[Link] 20/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
[Link]('error', function(err) {
[Link]([Link]);
});
[Link]("Program Ended");
Piping is a mechanism where we provide the output of one stream as the input to another stream. It is normally used to get data from one
stream and to pass the output of that stream to another stream. There is no limit on piping operations.
const fs = require("fs");
[Link]("Program Ended");
Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally
used with piping operations.
const fs = require("fs");
const zlib = require('zlib');
[Link]("File Compressed.");
↥ back to top
# 8. [Link] MULTITHREADING
Moreover, [Link] has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at
the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.
[Link] 21/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
To explain it practically, let's assume there are 100s of requests lined up in [Link] queue. As per design, the main thread of [Link] event loop
will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks
get notified on event loop thread to pass the result back to the user.
↥ back to top
↥ back to top
Q. How does [Link] support multi-processor platforms, and does it fully utilize all processor
resources?
Since [Link] is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core
resources. However, [Link] provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster
module is one of the core [Link] modules and it allows running multiple [Link] worker processes that will share the same port.
The cluster module helps to spawn new processes on the operating system. Each process works independently, so you cannot use shared state
between child processes. Each process communicates with the main process by IPC and pass server handles back and forth.
The main process listens on a port, accepts new connection and assigns it to a child process in a round robin fashion.
The main process assigns the port to a child process and child process itself listen the port.
↥ back to top
Q. Since node is a single threaded process, how to make use of all CPUs?
[Link] is a single threaded language which in background uses multiple threads to execute asynchronous code. [Link] is non-blocking which
means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads. That is handled by
[Link] run-time.
[Link] does support forking multiple processes ( which are executed on different cores ).
It is important to know that state is not shared between master and forked process.
We can pass messages to forked process ( which is different script ) and to master process from forked process with function send.
A single instance of [Link] runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster
of [Link] processes to handle the load. The cluster module allows easy creation of child processes that all share server ports.
if ([Link]) {
[Link](`Master ${[Link]} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
[Link]();
[Link] 22/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
}
Running [Link] will now share port 8000 between the workers:
$ node [Link]
Master 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started
The worker processes are spawned using the child_process.fork() method, so that they can communicate with the parent via IPC and pass
server handles back and forth.
The first one (and the default one on all platforms except Windows), is the round-robin approach, where the master process listens on a port,
accepts new connections and distributes them across the workers in a round-robin fashion, with some built-in smarts to avoid overloading a
worker process.
The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept
incoming connections directly.
↥ back to top
As soon as Node js starts, it initializes an event loop. The event loop works on a queue (which is called an event queue) and performs tasks in
FIFO (First In First Out) order. It executes a task only when there is no ongoing task in the call stack. The call stack works in LIFO(Last In First
Out) order. The event loop continuously checks the call stack to check if there is any task that needs to be run. Now whenever the event loop
finds any function, it adds it to the stack and runs in order.
Example:
/**
* Concurrency
*/
function add(a, b) {
return a + b;
}
function print(n) {
[Link](`Two times the number ${n} is ` + add(n, n));
}
print(5);
[Link] 23/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Here, the function print(5) will be invoked and will push into the call stack. When the function is called, it starts consoling the statement inside
it but before consoling the whole statement it encounters another function add(n,n) and suspends its current execution, and pushes the add
function into the top of the call stack.
Now the function will return the addition a+b and then popped out from the stack and now the previously suspended function will start
running and will log the output to console and then this function too will get pop from the stack and now the stack is empty. So this is how a
call stack works.
↥ back to top
Q. How to kill child processes that spawn their own child processes in [Link]?
If a child process in [Link] spawn their own child processes, kill() method will not kill the child process's own child processes. For example, if I
start a process that starts it's own child processes via child_process module, killing that child process will not make my program to quit.
[Link]();
The program above will not quit if my-command spins up some more processes.
We can start child processes with {detached: true} option so those processes will not be attached to main process but they will go to a new
group of processes. Then using [Link](-pid) method on main process we can kill all processes that are in the same group of a child process
with the same pid group. In my case, I only have one processes in this group.
[Link](-[Link]);
Please note - before pid. This converts a pid to a group of pids for process kill() method.
↥ back to top
↥ back to top
Syntax:
[Link] 24/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Header - Consists of two parts: the type of token (i.e., JWT) and the signing algorithm (i.e., HS512)
Payload - Contains the claims that provide information about a user who has been authenticated along with other information such as
token expiration time.
Signature - Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret
Installation:
Example:
/**
* [Link]
*/
const express = require('express');
const router = [Link]();
const bodyParser = require('body-parser');
const User = require('../user/User');
[Link]({
name : [Link],
email : [Link],
password : hashedPassword
},
function (err, user) {
if (err) return [Link](500).send("There was a problem registering the user.")
// create a token
let token = [Link]({ id: user._id }, [Link], {
expiresIn: 86400 // expires in 24 hours
});
[Link](200).send({ auth: true, token: token });
});
});
[Link]:
/**
* [Link]
*/
[Link] = {
'secret': 'supersecret'
};
The [Link]() method takes a payload and the secret key defined in [Link] as parameters. It creates a unique string of characters
representing the payload. In our case, the payload is an object containing only the id of the user.
Reference:
[Link]
↥ back to top
[Link] 25/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
There are few things worth emphasizing about the superiority of microservices, and distributed systems generally, over monolithic architecture:
Modularity — responsibility for specific operations is assigned to separate pieces of the application
Uniformity — microservices interfaces (API endpoints) consist of a base URI identifying a data object and standard HTTP methods (GET,
POST, PUT, PATCH and DELETE) used to manipulate the object
Robustness — component failures cause only the absence or reduction of a specific unit of functionality
Maintainability — system components can be modified and deployed independently
Scalability — instances of a service can be added or removed to respond to changes in demand.
Availability — new features can be added to the system while maintaining 100% availability.
Testability — new solutions can be tested directly in the production environment by implementing them for restricted segments of users
to see how they behave in real life.
This file is creating our server and assigns routes to process all requests.
// [Link]
The next step is to define the routes for the microservices and then assign each to a target in the controller. We have two endpoints. One
endpoint called "about" that returns information about the application. And a "distance" endpoint that includes two path parameters, both Zip
Codes of the Lego store. This endpoint returns the distance, in miles, between these two Zip Codes.
[Link] = function(app) {
[Link]('/about')
.get([Link]);
[Link]('/distance/:zipcode1/:zipcode2')
[Link] 26/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
.get([Link]);
};
Within the controller file, we are going to create a controller object with two properties. Those properties are the functions to handle the
requests we defined in the routes module.
const controllers = {
about: function(req, res) {
let aboutInfo = {
name: [Link],
version: [Link]
}
[Link](aboutInfo);
},
getDistance: function(req, res) {
[Link](req, res, function(err, dist) {
if (err)
[Link](err);
[Link](dist);
});
},
};
[Link] = controllers;
↥ back to top
↥ back to top
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware
function. Otherwise, the request will be left hanging.
[Link] 27/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Middleware functions that return a Promise will call next(value) when they reject or throw an error. next will be called with either the
rejected value or the thrown Error.
↥ back to top
Example:
To load the middleware function, call [Link]() , specifying the middleware function. For example, the following code loads the myLogger
middleware function before the route to the root path (/).
/**
* myLogger
*/
const express = require("express");
const app = express();
[Link](myLogger);
[Link](3000);
↥ back to top
Features of [Link]:
Fast Server-Side Development: The features of node js help express saving a lot of time.
Middleware: Middleware is a request handler that has access to the application's request-response cycle.
Routing: It refers to how an application's endpoint's URLs respond to client requests.
Templating: It provides templating engines to build dynamic content on the web pages by creating HTML templates on the server.
Debugging: Express makes it easier as it identifies the exact part where bugs are.
[Link] 28/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
The [Link] framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET,
PUT, and POST and DELETE requests.
Example:
/**
* Simple server using [Link]
*/
const express = require("express");
const app = express();
↥ back to top
/**
* [Link]
*/
const app = express();
[Link]([Link]());
[Link]("/api/events", [Link]);
[Link]("/api/forms", forms);
/**
* [Link]
*/
const app = require('../app');
const http = require('http');
↥ back to top
Package Description
Async Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript
Browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the
Browserify
browser in a single <script> tag
[Link] 29/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Package Description
Bower is a package manager for the web It works by fetching and installing packages from all over, taking care of hunting,
Bower
finding, downloading, and saving the stuff you're looking for
Csv csv module has four sub modules which provides CSV generation, parsing, transformation and serialization for [Link]
Debug Debug is a tiny [Link] debugging utility modelled after node core's debugging technique
Express is a fast, un-opinionated, minimalist web framework. It provides small, robust tooling for HTTP servers, making it a
Express
great solution for single page applications, web sites, hybrids, or public HTTP APIs
is a JavaScript Task Runner that facilitates creating new projects and makes performing repetitive but necessary tasks such
Grunt
as linting, unit testing, concatenating and minifying files (among other things) trivial
Gulp is a streaming build system that helps you automate painful or time-consuming tasks in your development workflow
Hapi is a streaming build system that helps you automate painful or time-consuming tasks in your development workflow
is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it's simple and
Http-server
hackable enough to be used for testing, local development, and learning
Static analysis tool to detect errors and potential problems in JavaScript code and to enforce your team's coding
Jshint
conventions
Koa is web app framework. It is an expressive HTTP middleware for [Link] to make web applications and APIs more
Koa
enjoyable to write
The lodash library exported as a node module. Lodash is a modern JavaScript utility library delivering modularity,
Lodash
performance, & extras
Moment A lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates
MongoDB The official MongoDB driver for [Link]. It provides a high-level API on top of mongodb-core that is meant for end users
It is a simple monitor script for use during development of a [Link] app, It will watch the files in the directory in which
Nodemon
nodemon was started, and if any files change, nodemon will automatically restart your node application
An NPM installer for PhantomJS, headless webkit with JS API. It has fast and native support for various web standards: DOM
Phantomjs
handling, CSS selector, JSON, Canvas, and SVG
A simple, unobtrusive authentication middleware for [Link]. Passport uses the strategies to authenticate requests.
Passport
Strategies can range from verifying username and password credentials or authentication using OAuth or OpenID
Q is a library for promises. A promise is an object that represents the return value or the thrown exception that the function
Q
may eventually provide
Request is Simplified HTTP request client make it possible to make http calls. It supports HTTPS and follows redirects by
Request
default
Sails Sails is a API-driven framework for building realtime apps, using MVC conventions (based on Express and [Link])
Through It enables simplified stream construction. It is easy way to create a stream that is both readable and writable
[Link] is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map,
Underscore
reduce, filter...) without extending any core JavaScript objects
[Link] 30/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Package Description
Ws A simple to use, blazing fast and thoroughly tested websocket client, server and console for [Link]
Bindings for [Link] and [Link] to ZeroMQ. It is a high-performance asynchronous messaging library, aimed at use in
Zmq
distributed or concurrent applications
↥ back to top
1. npm outdated
2. Trace by RisingStack
3. NSP
4. GreenKeeper
5. Snyk
6. npm audit
7. npm audit fix
↥ back to top
Helmet helps to secure your Express applications by setting various HTTP headers, like:
/**
* Helmet
*/
const express = require('express')
const helmet = require('helmet')
const app = express()
[Link](helmet())
2. JOI module:
Validating user input is one of the most important things to do when it comes to the security of your application. Failing to do it correctly can
open up your application and users to a wide range of attacks, including command injection, SQL injection or stored cross-site scripting.
To validate user input, one of the best libraries you can pick is joi. Joi is an object schema description language and validator for JavaScript
objects.
/**
* Joi
*/
const Joi = require('joi');
[Link] 31/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
const schema = [Link]().keys({
username: [Link]().alphanum().min(3).max(30).required(),
password: [Link]().regex(/^[a-zA-Z0-9]{3,30}$/),
access_token: [[Link](), [Link]()],
birthyear: [Link]().integer().min(1900).max(2013),
email: [Link]().email()
}).with('username', 'birthyear').without('password', 'access_token')
// Return result
const result = [Link]({
username: 'abc',
birthyear: 1994
}, schema)
// [Link] === null -> valid
3. Regular Expressions:
Regular Expressions are a great way to manipulate texts and get the parts that you need from them. However, there is an attack vector called
Regular Expression Denial of Service attack, which exposes the fact that most Regular Expression implementations may reach extreme situations
for specially crafted input, that cause them to work extremely slowly.
The Regular Expressions that can do such a thing are commonly referred as Evil Regexes. These expressions contain: *grouping with repetition,
*inside the repeated group: *repetition, or *alternation with overlapping
(a+)+
([a-zA-Z]+)*
(a|aa)+
4. [Link]:
[Link] defines a standard to help organizations define the process for security researchers to securely disclose security vulnerabilities.
[Link]('/[Link]', securityTxt({
// your security address
contact: 'email@[Link]',
// your pgp key
encryption: 'encryption',
// if you have a hall of fame for securty resourcers, include the link here
acknowledgements: '[Link]
}))
↥ back to top
It works as an Online repository for [Link] packages/modules which are present at <[Link]>.
It works as Command line utility to install packages, do version management and dependency management of [Link] packages. NPM
comes bundled along with [Link] installable. We can verify its version using the following command-
npm --version
NPM helps to install any [Link] module using the following command.
[Link] 32/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
For example, following is the command to install a famous [Link] web framework module called express-
↥ back to top
After installing packages using npm install or npm install <package-name> and updating your node_modules folder, you should run
npm shrinkwrap
It should create new [Link] file with information about all packages you use. Next time, when someone calls npm install, it will
install packages from [Link] and you will have the same environment on all machines.
↥ back to top
2. [Link]:
/**
* File Upload in [Link]
*/
const express = require("express");
const bodyParser = require("body-parser");
const multer = require("multer");
const app = express();
[Link] 33/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
});
[Link](3000, function () {
[Link]("Listening on port 3000");
});
3. [Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Multer-File-Upload</title>
</head>
<body>
<h1>MULTER File Upload | Single File Upload</h1>
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/photo"
method = "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
↥ back to top
body-parser extract the entire body portion of an incoming request stream and exposes it on [Link] . The body-parser module parses the
JSON, buffer, string and URL encoded data submitted using HTTP POST request.
Example:
/**
* body-parser
*/
const express = require("express");
const bodyParser = require("body-parser");
2. cookie-parser:
[Link] 34/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is
currently using.
The cookie-parser middleware's cookieParser function takes a secret string or array of strings as the first argument and an options object
as the second argument.
Installation:
Example:
/**
* cookie-parser
*/
const express = require('express')
const cookieParser = require('cookie-parser')
[Link](3000)
3. morgan:
Installation:
Example:
/**
* Writing logs to a file
*/
const express = require('express')
const fs = require('fs')
const morgan = require('morgan')
const path = require('path')
4. nodemon:
Nodemon is a utility that will monitor for any changes in source and automatically restart your server.
Installation:
[Link] 35/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Example:
{
// ...
"scripts": {
"start": "nodemon [Link]"
},
// ...
}
5. pm2:
P(rocess) M(anager) 2 (pm2) is a production process manager for [Link] applications with a built-in load balancer. It allows to keep
applications alive forever, to reload them without downtime and to facilitate common system admin tasks.
Installation:
Start an application:
Reference:
[Link]
6. serve-favicon:
[Link] middleware for serving a favicon. It create new middleware to serve a favicon from the given path to a favicon file. path may also be a
Buffer of the icon to serve.
Installation:
Example:
/**
* serve-favicon
*/
const express = require('express')
const favicon = require('serve-favicon')
const path = require('path')
[Link](3000)
7. cors:
Cross-Origin Resource Sharing (CORS) headers allow apps running in the browser to make requests to servers on different domains (also
known as origins). CORS headers are set on the server side - the HTTP server is responsible for indicating that a given HTTP request can be
cross-origin.
Installation:
[Link] 36/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Example:
/**
* Enable CORS for a Single Route
*/
const express = require('express')
const cors = require('cors')
const app = express()
[Link](8080, function () {
[Link]('CORS-enabled web server listening on port 80')
})
8. dotenv:
When a NodeJs application runs, it injects a global variable called [Link] which contains information about the state of environment in
which the application is running. The dotenv loads environment variables stored in the .env file into [Link] .
Installation:
Usage:
// .env
DB_HOST=localhost
DB_USER=admin
DB_PASS=root
/**
* [Link]
*/
const db = require('db')
[Link]({
host: [Link].DB_HOST,
username: [Link].DB_USER,
password: [Link].DB_PASS
})
9. fs-extra:
fs-extra contains methods that aren't included in the vanilla [Link] fs package. Such as recursive mkdir , copy , and remove . It also uses
graceful-fs to prevent EMFILE errors.
Installation:
Usage:
/**
* fs-extra
*/
const fs = require('fs-extra')
[Link] 37/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
// Async with callbacks:
[Link]('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return [Link](err)
[Link]('success!')
})
10. moment:
A JavaScript date library for parsing, validating, manipulating, and formatting dates.
Installation:
Usage:
Format Dates
Relative Time
Calendar Time
↥ back to top
HTTP methods:
Example:
[Link] 38/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
// [Link]
{
"user1" : {
"id": 1,
"name" : "Ehsan Philip",
"age" : 24
},
"user2" : {
"id": 2,
"name" : "Karim Jimenez",
"age" : 22
},
"user3" : {
"id": 3,
"name" : "Giacomo Weir",
"age" : 18
}
}
Let's implement our first RESTful API listUsers using the following code in a [Link] file −
Following API will show you how to add new user in the list.
const user = {
"user4" : {
"id": 4,
"name" : "Spencer Amos",
"age" : 28
}
}
[Link] 39/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
const host = [Link]().address
const port = [Link]().port
[Link]("App listening at [Link] host, port)
})
Delete User:
const id = 2;
↥ back to top
A [Link] is a part of a URL that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a
Web browser or other client application, for example as part of an HTML form. A query is the last part of URL
/**
* [Link]
*/
// GET [Link]
/**
* [Link]
*/
// GET [Link]
↥ back to top
[Link] 40/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
/**
* POST Request
*/
const request = require("request");
↥ back to top
Promises in [Link] promised to do some work and then had separate callbacks that would be executed for success and failure as well as
handling timeouts. Another way to think of promises in [Link] was that they were emitters that could emit only two events: success and
[Link] cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B
complete).
The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different
states:
Creating a Promise:
↥ back to top
Q. How can you secure your HTTP cookies against XSS attacks?
1. When the web server sets cookies, it can provide some additional attributes to make sure the cookies won't be accessible by using malicious
JavaScript. One such attribute is HttpOnly.
HttpOnly makes sure the cookies will be submitted only to the domain they originated from.
2. The "Secure" attribute can make sure the cookies are sent over secured channel only.
3. The web server can use X-XSS-Protection response header to make sure pages do not load when they detect reflected cross-site scripting
(XSS) attacks.
[Link] 41/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
X-XSS-Protection: 1; mode=block
4. The web server can use HTTP Content-Security-Policy response header to control what resources a user agent is allowed to load for a certain
page. It can help to prevent various types of attacks like Cross Site Scripting (XSS) and data injection attacks.
↥ back to top
const obj = {
"userId":1,
"id":1,
"title":"whatever",
"completed":false
}
const options = {
hostname: '[Link]',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': [Link]
}
}
[Link]('data', d => {
[Link](d)
})
})
[Link](data)
[Link]()
↥ back to top
↥ back to top
[Link] 42/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
The architecture of asynchronous explains that the message sent will not give the reply on immediate basis just like we send the mail but do
not get the reply on an immediate basis. It does not have any dependency or order. Hence improving the system efficiency and performance.
The server stores the information and when the action is done it will be notified.
2. Non-Blocking:
Nonblocking immediately responses with whatever data available. Moreover, it does not block any execution and keeps on running as per the
requests. If an answer could not be retrieved then in those cases API returns immediately with an error. Nonblocking is mostly used with
I/O(input/output). [Link] is itself based on nonblocking I/O model. There are few ways of communication that a nonblocking I/O has
completed. The callback function is to be called when the operation is completed. Nonblocking call uses the help of javascript which provides a
callback function.
↥ back to top
Blocking is when the execution of additional JavaScript in the [Link] process must wait until a non-JavaScript operation completes. This
happens because the event loop is unable to continue running JavaScript while a blocking operation is occurring.
Synchronous methods in the [Link] standard library that use libuv are the most commonly used blocking operations. Native modules may
also have blocking methods. Blocking methods execute synchronously and non-blocking methods execute asynchronously .
Example:
// Blocking
const fs = require('fs');
const data = [Link]('/[Link]'); // blocks here until file is read
[Link](data);
moreWork(); // will run after [Link]
// Non-blocking
const fs = require('fs');
[Link]('/[Link]', (err, data) => {
if (err) throw err;
[Link](data);
});
moreWork(); // will run before [Link]
↥ back to top
1. Blocking functions:
In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute
synchronously.
Example:
const fs = require('fs');
const data = [Link]('/[Link]'); // blocks here until file is read
[Link](data);
// moreWork(); will run after [Link]
The second line of code blocks the execution of additional JavaScript until the entire file is read. moreWork () will only be called after
[Link]
2. Non-blocking functions:
[Link] 43/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted. Non-blocking functions
execute asynchronously.
Example:
const fs = require('fs');
[Link]('/[Link]', (err, data) => {
if (err) throw err;
[Link](data);
});
// moreWork(); will run before [Link]
Since [Link]() is non-blocking, moreWork() does not have to wait for the file read to complete before being called. This allows for
higher throughput.
↥ back to top
In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is
requesting that the stored version be replaced.
With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should
be modified to produce a new version.
Also, another difference is that when you want to update a resource with PUT request, you have to send the full payload as the request whereas
with PATCH, you only send the parameters which you want to update.
The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database.
We specify these HTTP verbs in the capital case. So, the below is the comparison between them.
POST - create
GET - read
PUT - update
DELETE - delete
PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH
method.
↥ back to top
[Link]
require('http').METHODS
[ 'ACL',
'BIND',
'CHECKOUT',
'CONNECT',
'COPY',
'DELETE',
'GET',
'HEAD',
'LINK',
'LOCK',
'M-SEARCH',
[Link] 44/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
'MERGE',
'MKACTIVITY',
'MKCALENDAR',
'MKCOL',
'MOVE',
'NOTIFY',
'OPTIONS',
'PATCH',
'POST',
'PROPFIND',
'PROPPATCH',
'PURGE',
'PUT',
'REBIND',
'REPORT',
'SEARCH',
'SUBSCRIBE',
'TRACE',
'UNBIND',
'UNLINK',
'UNLOCK',
'UNSUBSCRIBE' ]
http.STATUS_CODES
require('http').STATUS_CODES
{ '100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'205': 'Reset Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'226': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'425': 'Unordered Collection',
'426': 'Upgrade Required',
[Link] 45/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'509': 'Bandwidth Limit Exceeded',
'510': 'Not Extended',
'511': 'Network Authentication Required' }
The first argument to request can either be a URL string, or an object of options. Here are some of the more common options you'll encounter
in your applications:
const options = {
url: '[Link]
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
Using the options object, this request uses the GET method to retrieve JSON data directly from Reddit, which is returned as a string in the body
field. From here, you can use [Link] and use the data as a normal JavaScript object.
↥ back to top
A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to
completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an
async request is completed. This way, other operations can keep running without interruption.
States of Promises:
[Link] 46/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Resolved : Completed Promise
Example:
function logFetch(url) {
return fetch(url)
.then(response => {
[Link](response);
})
.catch(err => {
[Link]('fetch failed', err);
});
}
2. Async-Await:
Await is basically syntactic sugar for Promises. It makes asynchronous code look more like synchronous/procedural code, which is easier for
humans to understand.
Putting the keyword async before a function tells the function to return a Promise. If the code returns something that is not a Promise , then
JavaScript automatically wraps it into a resolved promise with that value. The await keyword simply makes JavaScript wait until that Promise
settles and then returns its result.
Example:
↥ back to top
1. Async/Await:
Syntax
// Normal Function
function add(x,y){
return x + y;
}
// Async Function
async function add(x,y){
return x + y;
}
2. Await:
[Link] 47/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Async functions can make use of the await expression. This will pause the async function and wait for the Promise to resolve prior to moving
on.
Example:
function doubleAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x * 2);
}, 2000);
});
}
addAsync(10).then((sum) => {
[Link](sum);
});
↥ back to top
A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be
used as a proxy for a remote object to overcome latency.
Promise is relatively an easy implementation for asynchronous operation. The promise object returned from the function represents an
operation which is not completed yet, but it guarantees to the caller of the operation that the operation will be completed in future.
On the first pass, promises can mitigate the Pyramid of Doom: the situation where code marches to the right faster than it marches forward.
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
[Link](promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
[Link] 48/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done();
Reference:
[Link]
↥ back to top
ToDo
↥ back to top
These routing methods "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified
callback function.
Syntax:
[Link](PATH, HANDLER)
Where:
a) Route methods:
[Link] 49/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
b) Route paths:
Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string
patterns, or regular expressions.
The characters ? , + , * , and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted
literally by string-based paths.
Example:
c) Route parameters:
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are
populated in the [Link] object, with the name of the route parameter specified in the path as their respective keys.
Example:
Response methods:
Method Description
[Link]() Set the response status code and send its string representation as the response body.
d) Router method:
[Link] 50/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
})
[Link] = router
↥ back to top
[Link]('uncaughtException', function(err) {
[Link]('Caught exception: ' + err);
});
Process is a global object that provides information about the current [Link] process. Process is a listener function that is always listening to
events.
1. Exit
2. disconnect
3. unhandledException
4. rejectionHandled
↥ back to top
↥ back to top
[Link] 51/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Run
node-debug [Link]
2. Debugging:
Debugger
Node Inspector
Visual Studio Code
Cloud9
Brackets
3. Profiling:
4. Heapdumps:
5. Tracing:
6. Logging:
Caterpillar
Tracer
scribbles
Longjohn
↥ back to top
↥ back to top
Q. What is a stub?
Stubbing and verification for [Link] tests. Enables you to validate and override behaviour of nested pieces of code such as methods, require()
and npm modules or even instances of classes. This library is inspired on node-gently, MockJS and mock-require.
Features of Stub:
[Link] 52/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Compatible with Nodejs
Easily extendable directly or through an ExtensionManager
Comes with predefined, usable extensions
Stubs are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made
during test cases. Also, you can assert on with what these stubs were called.
A use-case can be a file read, when you do not want to read an actual file:
const fs = require('fs');
expect(readFileStub).[Link];
[Link]();
↥ back to top
Mike Cohn's original test pyramid consists of three layers that your test suite should consist of (bottom to top):
1. Unit Tests
2. Service Tests
3. User Interface Tests
↥ back to top
Example:
function validateUser(user) {
username: [Link]().min(5).max(30).required(),
email: [Link]().email().min(5).max(50).optional(),
[Link] 53/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
date_of_birth: [Link]().optional(),
account_status: [Link]()
.valid("activated")
.valid("unactivated")
.optional(),
}).options({ abortEarly: false });
return [Link](user);
}
const user = {
username: "Deepak Lucky",
email: "[Link]@[Link]",
date_of_birth: "2000-07-07",
account_status: "activated",
};
if ([Link]) {
[Link]([Link]);
} else {
[Link]("Validated Data");
}
The [Link] Crypto module supports cryptography. It provides cryptographic functionality that includes a set of wrappers for open SSL's hash
HMAC, cipher, decipher, sign and verify functions.
Hash: A hash is a fixed-length string of bits i.e. procedurally and deterministically generated from some arbitrary block of source data.
HMAC: HMAC stands for Hash-based Message Authentication Code. It is a process for applying a hash algorithm to both data and a secret
key that results in a single final hash.
[Link](encrypted);
[Link] 54/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
[Link](decrypted);
↥ back to top
↥ back to top
Q. What is REPL?
REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL
environment when it is installed. System interacts with the user through outputs of commands/expressions used. It is useful in writing and
debugging the codes. The work of REPL can be understood from its full form:
Read: It reads the inputs from users and parses it into JavaScript data structure. It is then stored to memory.
Eval: The parsed JavaScript data structure is evaluated for the results.
Print: The result is printed after the evaluation.
Loop: Loops the input command. To come out of NODE REPL, press ctrl+c twice
Simple Expression
$ node
> 10 + 20
30
> 10 + ( 20 * 30 ) - 40
570
>
↥ back to top
The [Link] runtime for App Engine in the standard environment is declared in the [Link] file:
runtime: nodejs10
The runtime environment is literally just the environment your application is running in. This can be used to describe both the hardware and the
software that is running your application. How much RAM, what version of node, what operating system, how much CPU cores, can all be
referenced when talking about a runtime environment.
↥ back to top
[Link] 55/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
For example, when we work on a project and there are production and development environments. We don't need to use caching in the
development env. So we set
NODE_ENV=development
↥ back to top
// Sample usage
↥ back to top
[Link] 56/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
[Link](`reverse for ${a}: ${[Link](hostnames)}`);
});
});
});
↥ back to top
[Link] has depended on the V8 JavaScript engine to provide code execution in the language. The V8 is a JavaScript engine built at the google
development center, in Germany. It is open source and written in C++. It is used for both client side (Google Chrome) and server side ([Link])
JavaScript applications. A central piece of the V8 engine that allows it to execute JavaScript at high speed is the JIT (Just In Time) compiler. This
is a dynamic compiler that can optimize code during runtime. When V8 was first built the JIT Compiler was dubbed FullCodegen. Then, the V8
team implemented Crankshaft, which included many performance optimizations that FullCodegen did not implement.
The V8 was first designed to increase the performance of the JavaScript execution inside web browsers. In order to obtain speed, V8 translates
JavaScript code into more efficient machine code instead of using an interpreter. It compiles JavaScript code into machine code at execution by
implementing a JIT (Just-In-Time) compiler like a lot of modern JavaScript engines such as SpiderMonkey or Rhino (Mozilla) are doing. The
main difference with V8 is that it doesn't produce bytecode or any intermediate code.
↥ back to top
↥ back to top
↥ back to top
We can store data to memcached server in key pair format. So whenever any request come from the app can be matched with memcached
server without any query from mysql/Nosql server. This increases the performance of the application.
Installation:
The constructor of the memcached client take 2 different arguments server locations and options. Syntax:
[Link] 57/58
4/10/25, 3:41 PM GitHub - Mohamed-Hashem/nodejs-interview-questions: [Link] Interview Questions ( v16.x )
Example:
Releases
No releases published
Packages
No packages published
Languages
[Link] 58/58