Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
82 views

NodeJS Interview Questions

Node.js is a JavaScript runtime environment that achieves low latency and high throughput by taking a 'non-blocking' approach to serving requests. It uses an event loop which processes requests asynchronously without blocking and allows concurrent processing unlike other frameworks that use thread management. Common ways to run synchronous processes in Node.js include promises, async/await and callback functions.

Uploaded by

akshay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

NodeJS Interview Questions

Node.js is a JavaScript runtime environment that achieves low latency and high throughput by taking a 'non-blocking' approach to serving requests. It uses an event loop which processes requests asynchronously without blocking and allows concurrent processing unlike other frameworks that use thread management. Common ways to run synchronous processes in Node.js include promises, async/await and callback functions.

Uploaded by

akshay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Q1. How we can improve NodeJs security?

Ans. https://blog.bitsrc.io/6-best-practices-to-improve-node-js-security-d5796381b019

https://www.mindinventory.com/blog/nodejs-security-best-practices/

https://www.simform.com/blog/nodejs-security/

Q2. How to create child process in NodeJs?

Ans.
https://www.freecodecamp.org/news/node-js-child-processes-everything-you-need-to-kn
ow-e69498fe970a/

https://www.geeksforgeeks.org/node-js-child-process/

Q3. Sql query for find the second largest age from database.

Ans. SELECT MAX(age) from users where age < SELECT MAX(age) from users

Q4. What is the disadvantage of NodeJs?

Ans:-
https://anywhere.epam.com/business/node-js-pros-and-cons.

https://www.simform.com/blog/nodejs-advantages-disadvantages/

https://www.mindinventory.com/blog/pros-and-cons-of-node-js-web-app-development/
Q5. What is the disadvantage of recursive function?

Ans.
https://www.educative.io/courses/recursion-for-coding-intervi
ews-in-cpp/qAx1lwQYDNG

Q6. What are the features of ES6?

ANS.
https://www.boardinfinity.com/blog/top-10-features-of-es6/

Q7. What are the difference between PUT and PATCH


methods?

ANS.
https://www.geeksforgeeks.org/difference-between-put-and-p
atch-request/

Q8. What are the features of NodeJS 20?

ANS.
https://betterprogramming.pub/6-major-features-of-node-js-2
0-741a206cb84

https://www.bacancytechnology.com/blog/whats-new-in-node
-20
(1) How does node js process multiple requests at a time?

Given a NodeJS application, since Node is single-threaded, say if


processing involves a Promise.all that takes 8 seconds, does this mean
that the client request that comes after this request would need to wait for
eight seconds? No. NodeJS event loop is single-threaded. The entire
server architecture for NodeJS is not single-threaded.

Before getting into the Node server architecture, to take a look at typical
multithreaded request-response model, the web server would have multiple
threads and when concurrent requests get to the webserver, the webserver
picks threadOne from the threadPool and threadOne processes
requestOne and responds to clientOne and when the second request
comes in, the web server picks up the second thread from the threadPool
and picks up requestTwo and processes it and responds to clientTwo.
threadOne is responsible for all kinds of operations that requestOne
demanded including doing any blocking IO operations.

The fact that the thread needs to wait for blocking IO operations is what
makes it inefficient. With this kind of a model, the webserver is only able to
serve as many requests as there are threads in the thread pool.

NodeJS Web Server maintains a limited Thread Pool to provide services to


client requests. Multiple clients make multiple requests to the NodeJS
server. NodeJS receives these requests and places them into the
EventQueue . NodeJS server has an internal component referred to as the
EventLoop which is an infinite loop that receives requests and processes
them. This EventLoop is single threaded. In other words, EventLoop is the
listener for the EventQueue. So, we have an event queue where the
requests are being placed and we have an event loop listening to these
requests in the event queue. What happens next? The listener(the event
loop) processes the request and if it is able to process the request without
needing any blocking IO operations, then the event loop would itself
process the request and send the response back to the client by itself. If
the current request uses blocking IO operations, the event loop sees
whether there are threads available in the thread pool, picks up one thread
from the thread pool and assigns the particular request to the picked
thread. That thread does the blocking IO operations and sends the
response back to the event loop and once the response gets to the event
loop, the event loop sends the response back to the client.

How is NodeJS better than traditional multithreaded request response


model? With traditional multithreaded request/response model, every client
gets a different thread where as with NodeJS, the simpler request are all
handled directly by the EventLoop. This is an optimization of thread pool
resources and there is no overhead of creating the threads for every client
request.
(2) How to improve node js application performance?

(1) Caching your app with Redis.


(2) Make sure your query is optimized.
(3) Check app error scripts with logging.
(4) Implement HTTP/2
(5) Clustering your Node.js application.
(6) Use real-time app monitor to analysis your app.

Resources:
https://medium.com/skyshidigital/6-tricks-to-speed-up-and-improve-your-no
de-js-performance-fadc06d15cbe
(3) How node js Event Loop internally works ?
https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

(4) What is Node js and how it works ?

Node.js is a JavaScript runtime environment that achieves low latency


and high throughput by taking a “non-blocking” approach to serving requests.

Node.js is made of Chrome V8 engine which is written in c++ and Libuv


which is a multi-platform C library that provides support for asynchronous I/O
based events on event loops and thread loops.

(5) How is Node.js better than other frameworks most


popularly used ?

Node.js provides simplicity in development because of its non-blocking I/O and


event-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.

(6) What is the way to do synchronous process using node js


?
Promise, async await and callback functions.

(7) What is you prefer Promise or async await as a developer


?

We can use either of both. But I use promise because structure of code is well.
And we can easily read the code.

(8) Can you explain Async.parallel or Async.series or that


kind of functionality?

Async.Parallel: When we have to run multiple tasks independent of each other


without waiting until the previous task has been completed, Async.parallel comes into
the picture.

Tasks: A collection of functions to run. It can be an array, an object or any iterable.

Callback: This is the callback where all the task results are passed and is executed once
all the task execution has been completed.

In case an error is passed to a function’s callback, the main callback is immediately


called with the error.

An example of parallel:

async.parallel(
[

function(callback) {

setTimeout(function() {

console.log('Task One');

callback(null, 1);
}, 200);

},

function(callback) {

setTimeout(function() {

console.log('Task Two');

callback(null, 2);

}, 100);

],

function(err, results) {

console.log(results);

// the results array will equal [1, 2] even


though

// the second function had a shorter


timeout.

});

// an example using an object instead of an


array
async.parallel({

task1: function(callback) {

setTimeout(function() {

console.log('Task One');

callback(null, 1);

}, 200);

},

task2: function(callback) {

setTimeout(function() {

console.log('Task Two');

callback(null, 2);

}, 100);

}, function(err, results) {

console.log(results);

// results now equals to: { task1: 1, task2:


2 }

});

Async.series: When we have to run multiple tasks which depend on the output of the
previous task, series comes to our rescue.

Tasks: A collection of functions to run. It can be an array, an object or any iterable.


Callback: This is the callback where all the task results are passed and is executed once
all the task execution has completed.

Callback function receives an array of result objects when all the tasks have
been completed. If an error is encountered in any of the task, no more
functions are run but the final callback is called with the error value.

Example:

async.series
([

function(callback) {

console.log('one');

callback(null, 1);

},

function(callback) {

console.log('two');

callback(null, 2);

},

function(callback) {

console.log('three');

callback(null, 3);

],

function(err, results) {
console.log(result);

// results is now equal to [1, 2, 3]

});

async.series({

1: function(callback) {

setTimeout(function() {

console.log('Task 1');

callback(null, 'one');

}, 200);

},

2: function(callback) {

setTimeout(function() {

console.log('Task 2');

callback(null, 'two');

}, 300);

},

3: function(callback) {

setTimeout(function() {

console.log('Task 3');

callback(null, 'three');

}, 100);
}

},

function(err, results) {

console.log(results);

// results is now equal to: { 1: 'one', 2:


'two', 3:'three' }

});

Async.waterfall: When we have to run multiple tasks which depend on the


output of previous task, Waterfall can be helpful.

Tasks: A collection of functions to run. It can be an array, an object or any


iterable structure.

Callback: This is the callback where all the task results are passed and is
executed once all the task execution has completed.

It will run one function at a time and pass the result of the previous function to
the next one.

Example:

async.waterfal
l([

function(callback) {

callback(null, 'Task 1', 'Task 2');

},

function(arg1, arg2, callback) {


// arg1 now equals 'Task 1' and arg2 now
equals 'Task 2'

let arg3 = arg1 + ' and ' + arg2;

callback(null, arg3);

},

function(arg1, callback) {

// arg1 now equals 'Task1 and Task2'

arg1 += ' completed';

callback(null, arg1);

], function(err, result) {

// result now equals to 'Task1 and Task2


completed'

console.log(result);

});

// Or, with named functions:

async.waterfall([

myFirstFunction,

mySecondFunction,

myLastFunction,

], function(err, result) {
// result now equals 'Task1 and Task2
completed'

console.log(result);

});

function myFirstFunction(callback) {

callback(null, 'Task 1', 'Task 2');

function mySecondFunction(arg1, arg2,


callback) {

// arg1 now equals 'Task 1' and arg2 now


equals 'Task 2'

let arg3 = arg1 + ' and ' + arg2;

callback(null, arg3);

function myLastFunction(arg1, callback) {

// arg1 now equals 'Task1 and Task2'

arg1 += ' completed';

callback(null, arg1);

Reference :
https://www.velotio.com/engineering-blog/understanding-node-js-async-flows-parallel-s
erial-waterfall-and-queues
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Displayin
g_data/flow_control_using_async#why_is_this_needed

(9) Can you explain promise.all like this functionality ?

Promise.All: This method can be useful for aggregating the results of


multiple promises. It is typically used when there are multiple related
asynchronous tasks that the overall code relies on to work successfully —
all of whom we want to fulfill before the code execution continues.

Promise.all() will reject immediately upon any of the input promises rejecting.

Example:

const promise1 = Promise.resolve(3);


const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {


console.log(values);
});
// expected output: Array [3, 42, "foo"]

If the iterable contains non-promise values, they will be ignored, but still
counted in the returned promise array value (if the promise is fulfilled):

(10) What are the globles which are directly provided from
nodejs ?
Node.js global objects are global in nature and they are available in
all modules. We do not need to include these objects in our application,
rather we can use them directly. These objects are modules, functions,
strings and object itself as explained below.

Process module, __filename, __dirname these are the examples of the


nodejs globals.

(11) Is middleware is used request only or we can use


response as well ?

Middleware function is use request object, response object, and next function. So
I think we can use middleware for response object.

(12) How can you handle unhandled exceptions in nodejs ?

There are two approaches to handle the unhandled exception.


Approach 1: Using try-catch block: We know that Node.js is a platform built on
JavaScript runtime for easily building fast and scalable network applications.
Being part of JavaScript, we know that the most prominent way to handle the
exception is we can have try and catch block.
Note: However, be careful not to use try-catch in asynchronous code, as an
asynchronously thrown error will not be caught.

Approach 2: Using Process: A good practice says, you should use Process to
handle exceptions. A process is a global object that provides information about
the current Node.js process. The process is a listener function that is always
listening to the events.
The most effective and efficient approach is to use Process.

(13) API methods like POST, GET, PUT all about it.
An HTTP method is idempotent if an identical request can be made
once or several times in a row with the same effect while leaving the server
in the same state. In other words, an idempotent method should not have
any side-effects (except for keeping statistics). Implemented correctly, the
GET, HEAD, PUT, and DELETE methods are idempotent, but not the POST
method. All safe methods are also idempotent.

GET : The HTTP GET method requests a representation of the specified


resource. Requests using GET should only be used to request data (they
shouldn't include data).

POST : The HTTP POST method sends data to the server. The type of the
body of the request is indicated by the Content-Type header. The
difference between PUT and POST is that PUT is idempotent: calling it once
or several times successively has the same effect (that is no side effect),
where successive identical POST may have additional effects, like passing
an order several times.

PUT : PUT is used to send data to a server to create/update a


resource. The difference between POST and PUT is that PUT
requests are idempotent. That is, calling the same PUT request
multiple times will always produce the same result. In contrast,
calling a POST request repeatedly have side effects of creating
the same resource multiple times.

DELETE: The HTTP DELETE request method deletes the specified


resource.

PATCH: PATCH is a method of modifying resources where the client sends


partial data that is to be updated without modifying the entire data.
Only data that need to be modified if send in the request body as a
payload, it has LOW Bandwidth.
Resources:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

(14) What is the difference between npm and yarn ?

Resources:

https://www.geeksforgeeks.org/difference-between-npm-and-yarn/

(15) What is the difference between dependency and dev


dependency ?

Resources:

https://www.geeksforgeeks.org/difference-between-dependencies-devdepe
ndencies-and-peerdependencies/

(16) While selecting nodejs version what is the meaning of


LTS over there ?

It depends where you are using node.js in your apps and how
sensitive are they.

LTS (Long Term Support, currently v6.11.2) - as was mentioned in the


comment, will have support and maintenance for at least 18months. So it's
better to use this one in Production for node.js as a back-end service.
Stable (currently v8.3.0) - will have support for approximately 8months,
with features/updates released more often. This version will be ok for
Production if you're using node.js for front-end services (dependency
management etc.). Will work for node.js on back-end as well, if you have
ability to easily update your apps without interrupting the environment.
The reason of 2 type node.js versions:

As node.js team described when they announced this feature is that 2


different types of node.js versions will meet your node.js needs. Basically, if
you have a complex node.js app and you want stability, then stay on LTS. If
you are able to update your app often, or you use node.js only for the
front-end tools, then use Stable. The philosophy is to push new features,
performance updates, bug fixes etc. in a quick manner, so
companies/developers who wants the 'on the edge' technology and loves
node.js, will be able easily use it and expect updates every 2weeks.

Resources:
https://stackoverflow.com/questions/34829167/what-is-the-difference-betwe
en-the-lts-version-and-the-stable-version-of-node-js

(17) What is localization in nodejs?

We can use either of both. But I use promise because structure of code is well.
And we can

(18) Authentication and authorization process in nodejs. JWT


working process.

We can use either of both. But I use promise because structure of code is well.
And we can

Other Interview Questions and answers:

1. https://www.interviewbit.com/node-js-interview-questions/
2. https://www.simplilearn.com/tutorials/nodejs-tutorial/nodejs-interview-questions
3. https://github.com/learning-zone/nodejs-interview-questions
19. What is the difference between library and framework?

https://www.interviewbit.com/blog/framework-vs-library/
https://www.shiksha.com/online-courses/articles/framework-vs-library/

20. What is streams and buffers in NodeJS?

ANS. https://www.codingninjas.com/codestudio/library/streams-and-buffer-in-node-js

21. What is webSocket ?

ANS.
https://www.geeksforgeeks.org/what-is-web-socket-and-how-it-is-different-from-the-htt
p/

You might also like