AWS Community Day CPH - Three problems of Terraform
Node.JS Interview Questions Part-2.pdf
1. Node.JS Interview Questions
Part-2
In this article, we will discuss Node.js Interview Questions Part 2
51. How do you handle pagination in Node.js?
Solution: Pagination in Node.js can be achieved by using query parameters or
request headers to specify the page number and page size, and then applying
the appropriate logic in your database queries or data fetching functions.
52. What is the purpose of the DNS module in Node.js?
Solution: The DNS module in Node.js provides functions to perform DNS
(Domain Name System) lookups, resolve hostnames to IP addresses, and vice
versa.
53. How do you handle server-side rendering (SSR) in Node.js?
Solution: Server-side rendering in Node.js can be implemented using
frameworks like Next.js or by manually rendering templates or views on the
server and sending the pre-rendered HTML to the client.
54. What is the purpose of the crypto module in Node.js?
Solution: The crypto module in Node.js provides cryptographic functionality,
including encryption, decryption, hashing, digital signatures, and more, to
enhance the security of your applications.
2. 55. How do you handle concurrency in Node.js?
Solution: Concurrency in Node.js can be achieved through techniques like
using worker threads, implementing distributed task queues, or leveraging
asynchronous patterns and event-driven programming to handle multiple
operations simultaneously.
56.What is the purpose of the fs module in Node.js?
Solution: The fs module in Node.js provides functions for working with the file
system, allowing you to read, write, delete, and modify files and directories.
57.How do you handle real-time communication in Node.js?
Solution: Real-time communication in Node.js can be handled using libraries
like Socket.io or WebSockets to establish a persistent connection between the
server and clients, enabling real-time data exchange.
58.What is the purpose of the util.inspect function in Node.js?
Solution: The util.inspect function in Node.js is used to convert JavaScript
objects into strings, providing a convenient way to inspect and debug objects
during development.
59.How do you handle environment variables in Node.js?
Solution: Environment variables in Node.js can be accessed using the
process.env object, which allows you to read and set environment-specific
configuration values without hardcoding them in your code.
60.What is the purpose of the querystring module in Node.js?
3. Solution: The querystring module in Node.js provides functions to parse and
stringify URL query strings, allowing you to handle and manipulate query
parameters in your applications.
61.How do you handle data validation in Node.js?
Solution: Data validation in Node.js can be done using libraries like Joi, Yup,
or Validator.js, which provide validation rules and functions to validate and
sanitize user input or data.
62.What is the purpose of the util.inherits function in Node.js?
Solution: The util.inherits function in Node.js is used to inherit the prototype
methods from one constructor function into another, implementing classical
inheritance in JavaScript.
63.How do you handle server-side cookies in Node.js?
Solution: Server-side cookies in Node.js can be handled by using libraries like
cookie-parser or by manually setting the appropriate Set-Cookie header in the
server’s response.
64.What is the purpose of the EventEmitter class in Node.js?
Solution: The EventEmitter class in Node.js is a built-in class that allows you
to emit and listen for events within your applications, facilitating
communication between different parts of the system65.How do you handle
timeouts and retries in Node.js?
4. Solution: Timeouts and retries in Node.js can be implemented using
techniques like setting timeouts on operations, using libraries like node-retry
or implementing custom logic to retry failed operations with exponential
backoff.
66.What is the purpose of the util.deprecate function in Node.js?
Solution: The util.deprecate function in Node.js is used to mark a function or
feature as deprecated, displaying a warning message when the deprecated
function or feature is used in the code.
67.How do you handle database transactions in Node.js?
Solution: Database transactions in Node.js can be handled using transactions
provided by the database drivers or ORMs, ensuring atomicity, consistency,
isolation, and durability (ACID) properties during database operations.
68.What is the purpose of the process.nextTick function in Node.js?
Solution: The process.nextTick function in Node.js is used to schedule a
function to be executed on the next iteration of the event loop, immediately
after the current operation completes.
69.How do you handle authentication with JSON Web Tokens (JWT) in
Node.js?
Solution: Authentication with JWT in Node.js involves generating and signing
JWT tokens on the server, sending them to clients upon successful
authentication, and verifying and decoding the tokens for subsequent
requests.
5. 70.What is the purpose of the cluster module in Node.js?
Solution: The cluster module in Node.js allows you to create a cluster of
worker processes to distribute the load across multiple CPU cores, enhancing
the application’s performance and scalability.
71.How do you handle internationalization (i18n) in Node.js?
Solution: Internationalization in Node.js can be handled using libraries like
i18n, i18next, or by implementing custom logic to support different languages
and translations within your application.
72.What is the purpose of the stream module in Node.js?
Solution: The stream module in Node.js provides an interface for
implementing streaming data, allowing you to read or write data in chunks,
which is useful for processing large files or data sets.
73.How do you handle server-side caching in Node.js?
Solution: Server-side caching in Node.js can be implemented using techniques
like in-memory caching with libraries like Redis or Memcached, or by using
caching proxies like Varnish or CDN (Content Delivery Network) services.
Advertisement
74.What is the purpose of the worker_threads module in Node.js?
Solution: The worker_threads module in Node.js allows you to create and run
JavaScript code in separate threads, enabling parallel processing and
utilization of multiple CPU cores.
6. 75.How do you handle WebSocket authentication in Node.js?
Solution: WebSocket authentication in Node.js can be achieved by sending
authentication credentials within the initial WebSocket handshake or by
implementing custom authentication logic within the WebSocket server.
76.What is the purpose of the dns.promises module in Node.js?
Solution: The dns.promises module in Node.js provides promise-based
versions of the functions in the dns module, allowing you to perform DNS
lookups and resolution using promises instead of callbacks.
77.How do you handle server-sent events (SSE) in Node.js?
Solution: Server-sent events in Node.js can be handled by implementing a
server that sends events to connected clients using the EventSource API,
allowing real-time server-to-client communication.
78.What is the purpose of the http module’s http.Agent class in Node.js?
Solution: The http.Agent class in the http module of Node.js is used to manage
and control HTTP client connections, providing connection pooling and
reusability for improved performance.
79.How do you handle circular dependencies in Node.js modules?
Solution: Circular dependencies in Node.js modules can be avoided by
restructuring the code or using techniques like dependency injection, lazy
loading, or separating the dependencies into smaller, independent modules.
80.What is the purpose of the fs.promises module in Node.js?
7. Solution: The fs.promises module in Node.js provides promise-based versions
of the functions in the fs module, allowing you to work with the file system
using promises instead of callbacks.
81.How do you handle data encryption and decryption in Node.js?
Solution: Data encryption and decryption in Node.js can be achieved using the
crypto module, which provides functions for symmetric and asymmetric
encryption algorithms like AES, RSA, and more.
82.What is the purpose of the process module in Node.js?
Solution: The process module in Node.js provides information and control
over the current Node.js process, allowing you to access environment
variables, command-line arguments, exit the process, and more.
83.How do you handle request validation and sanitization in Node.js?
Solution: Request validation and sanitization in Node.js can be done using
libraries like Joi, express-validator, or by implementing custom validation and
sanitization logic in your routes or middleware.
84.What is the purpose of the util.format function in Node.js?
Solution: The util.format function in Node.js is used to format strings by
replacing placeholders with specified values, similar to the printf function in C
or other programming languages.
85.How do you handle long-running tasks in Node.js?
8. Solution: Long-running tasks in Node.js can be handled by using techniques
like worker threads, child processes, or by offloading the tasks to background
job queues or task schedulers like Bull, RabbitMQ, or Agenda.
86.What is the purpose of the child_process module in Node.js?
Solution: The child_process module in Node.js provides functionality to
spawn child processes, execute commands in the system shell, and
communicate with the spawned processes.
87.How do you handle serverless functions in Node.js?
Solution: Serverless functions in Node.js can be handled using serverless
frameworks like AWS Lambda, Azure Functions, or Google Cloud Functions,
where you write functions that run on-demand without managing server
infrastructure.
88.What is the purpose of the net module in Node.js?
Solution: The net module in Node.js provides low-level networking
capabilities, allowing you to create TCP servers, clients, and perform network
operations like socket programming.
89.How do you handle file uploads in Node.js?
Solution: File uploads in Node.js can be handled using middleware like
multer, which provides support for handling multipart/form-data requests
and saving uploaded files to the server.
90.What is the purpose of the os module’s os.cpus() method in Node.js?
9. Solution: The os.cpus() method in the os module of Node.js returns an array of
objects representing the CPU cores available on the system, providing
information such as speed, model, and times of CPU usage.
91.How do you handle WebSocket disconnects in Node.js?
Solution: WebSocket disconnects in Node.js can be handled by listening for
the close event on the WebSocket connection and performing the necessary
cleanup or notifying other connected clients.
92.What is the purpose of the Buffer class in Node.js?
Solution: The Buffer class in Node.js is used to handle binary data and
provides methods for creating, manipulating, and converting data in different
encodings.
93.How do you handle request rate limiting in Node.js?
Solution: Request rate limiting in Node.js can be implemented using
middleware like express-rate-limit or by custom code that tracks and limits
the number of requests from a client within a specific time period.
94.What is the purpose of the util.inspect function in Node.js?
Solution: The util.inspect function in Node.js is used to convert JavaScript
objects into formatted strings, allowing you to inspect and debug objects with
customizable options.
95.How do you handle email sending in Node.js?
10. Solution: Email sending in Node.js can be handled using libraries like
Nodemailer, which provides an easy way to send email messages using SMTP
or other email transport protocols.
96.What is the purpose of the http.ServerResponse class in Node.js?
Solution: The http.ServerResponse class in Node.js represents the server’s
response to an HTTP request and provides methods for sending data, setting
headers, and managing the response lifecycle.
97.How do you handle graceful shutdown in Node.js?
Solution: Graceful shutdown in Node.js involves implementing logic to
gracefully terminate the server, close database connections, and complete
ongoing operations before exiting the process, ensuring no data loss or abrupt
disruptions.
98.What is the purpose of the util.formatWithOptions function in Node.js?
Solution: The util.formatWithOptions function in Node.js is used to format
strings with customizable options, allowing you to specify formatting options
for placeholders in the string.
99.How do you handle data caching in Node.js?
Solution: Data caching in Node.js can be implemented using in-memory
caching with libraries like Redis or Memcached, where frequently accessed
data is stored in memory for faster retrieval.
100.What is the purpose of the https module in Node.js?
11. Solution: The https module in Node.js provides functionality to create an
HTTPS server or make HTTPS requests, allowing secure communication over
the HTTP protocol using SSL/TLS encryption.
Code Based Questions: –
1.Write a simple Node.js server that listens on port 3000 and responds with
“Hello, World!” when accessed.
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
server.listen(3000, 'localhost', () => {
console.log('Server running at http://localhost:3000/');
});
2. Create a function that reads a file asynchronously using the fs module in
Node.js.
const fs = require('fs');
function readFileAsync(filePath, callback) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
callback(err);
return;
}
callback(null, data);
});
}
// Usage example
readFileAsync('example.txt', (err, data) => {
12. if (err) {
console.error(err);
return;
}
console.log(data);
});
3. Implement a basic Express.js route that responds with a JSON object
containing a message.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({ message: 'Hello, World!' });
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
4. Write a function that makes an HTTP GET request using the axios library in
Node.js.
const axios = require('axios');
async function makeGetRequest(url) {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error(error);
throw error;
13. }
}
// Usage example
makeGetRequest('https://api.example.com/data')
.then(data => console.log(data))
.catch(error => console.error(error));
5. Create a simple middleware function in Express.js that logs the request
method and URL.
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log(`Method: ${req.method}, URL: ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
6. What will be the output of the following code?
const person = {
name: 'John',
age: 30,
city: 'New York'
};
14. for (const key in person) {
console.log(key);
}
name
age
city
7. What will be the output of the following code?
Advertisement
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled);
[2, 4, 6, 8, 10]
8. What will be the output of the following code?
const add = (x, y) => x + y;
console.log(add(5, 10, 15));
15
[Explanation: The function add accepts two parameters (x and y), but when it
is called with add(5, 10, 15), the additional argument 15 is ignored.]
15. 9. What will be the output of the following code?
const arr = [10, 20, 30, 40, 50];
const [first, second, ...rest] = arr;
console.log(first, second, rest);
10 20 [30, 40, 50]
[Explanation: Destructuring assignment is used to assign the first element of
the array to first, the second element to second, and the remaining elements to
the rest array.]
10. What will be the output of the following code?
function greet() {
console.log(name);
var name = 'John';
console.log(name);
}
greet();
undefined
John
[Explanation: When console.log(name) is executed before the name variable is
assigned, it prints undefined. The variable name is then assigned the value
‘John’, and the second console.log(name) statement prints ‘John’.]
16. Advertisement
11. What will be the output of the following code?
const x = 10;
function outer() {
const x = 20;
function inner() {
console.log(x);
}
return inner;
}
const innerFn = outer();
innerFn();
20
[Explanation: The variable x within the inner function refers to the closest
lexical scope, which is the outer function where x is assigned the value 20.]
12. What will be the output of the following code?
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((total, num) => total + num, 0);
console.log(sum);
15
17. [Explanation: The reduce method is used to calculate the sum of all the
elements in the array. The initial value 0 is provided as the second argument
to reduce, and the arrow function total + num accumulates the sum.]
13. What will be the output of the following code?
function sayHi() {
console.log('Hi!');
return () => console.log('Bye!');
}
const fn = sayHi();
fn();
Hi!
Bye!
[Explanation: The sayHi function logs ‘Hi!’ and returns an arrow function.
When fn is invoked, it executes the returned arrow function, which logs
‘Bye!’.]
14. What will be the output of the following code?
const obj = { a: 1, b: 2 };
const { a, b } = obj;
console.log(a, b);
1 2
18. [Explanation: Object destructuring is used to extract the values of a and b
from the obj object and assign them to the variables with the same names.]
15. What will be the output of the following code?
const name = 'John';
function greet() {
console.log(`Hello, ${name}!`);
const name = 'Jane';
console.log(`Hello, ${name}!`);
}
greet();
Hello, undefined!
Hello, Jane!
[Explanation: The variable name within the greet function is hoisted, which
means it is declared at the top of the function scope. However, the assignment
of ‘Jane’ to name occurs after the first console.log statement, leading to
undefined being printed for the first log statement.]