Download as pdf or txt
Download as pdf or txt
You are on page 1of 303

300+ NODE.

JS
Interview Questions and Answers

MCQ Format

Created by: Manish Dnyandeo Salunke


Online Format: https://bit.ly/online-courses-tests
What is Node.js primarily used for in web
development?
1. Data manipulation in databases
2. To make the site look good
3. Building network applications
4. Creating animations

Correct Response: Option 3


Explanation: Node.js is used primarily for building scalable network
applications, such as web servers. It's built on the Chrome V8 JavaScript
engine, and it can work on various platforms (Windows, Linux, Unix, Mac
OS X, etc.). It uses a non-blocking, event-driven I/O model, making it
particularly suitable for real-time applications.
Node.js follows which type of programming
model?
1. Object-oriented
2. Procedural
3. Functional
4. Event-driven

Correct Response: Option 4


Explanation: Node.js follows an event-driven programming model. This
means that Node.js waits for events and then triggers a callback function
when one of these events is detected. This model is particularly well suited
for handling asynchronous operations and allows Node.js to handle multiple
operations concurrently without the need for multithreading.
In the context of Node.js, what is the event loop?
1. An array of events
2. A data structure
3. A lifecycle of an event
4. An infinite loop that handles events

Correct Response: Option 4


Explanation: The event loop is a crucial part of Node.js. It's what allows
Node.js to perform non-blocking I/O operations. Despite JavaScript being
single-threaded, this feature enables Node.js to handle concurrent
operations, making it highly scalable. The event loop is a loop that can have
various types of events that it handles. When these events occur, the
associated callback function is pushed into a queue, and then, when the
stack is clear, the functions in the queue are executed.
How does the non-blocking I/O model in Node.js
differ from traditional I/O handling methods?
1. It performs all I/O operations at once
2. It can handle multiple requests simultaneously without waiting for tasks
to complete
3. It performs I/O operations without a computer
4. It doesn't allow any I/O operations

Correct Response: Option 2


Explanation: Traditional I/O handling methods are blocking, meaning the
program waits for the I/O operations to complete before it can proceed. This
can lead to inefficiency, especially when handling many I/O operations.
Node.js uses a non-blocking I/O model. It means that Node.js can handle
multiple I/O requests concurrently. It initiates the I/O operation and then
continues to handle other tasks without waiting for the operation to
complete. When the operation is complete, Node.js gets notified and
handles the result, making it more efficient when dealing with multiple I/O
operations.
What is the significance of the "require" function
in Node.js?
1. It is used to include HTML files
2. It is used to import images
3. It is used to include modules
4. It is used to import CSS files

Correct Response: Option 3


Explanation: In Node.js, the require() function is an in-built function used
to include modules that exist in separate files. The idea is to have well-
structured, modular code, instead of a large, monolithic codebase. When
you require a module, you are essentially including all the exports from
another JavaScript file. These modules can be both core modules that come
with Node.js by default or other modules that we install using npm (Node
Package Manager).
Can you explain how Node.js handles child
threads?
1. Node.js does not support child threads
2. Node.js supports child threads and runs everything in a single thread
3. Node.js can create child threads for computationally expensive tasks
using the "worker_threads" module
4. Node.js runs every module in a separate thread

Correct Response: Option 3


Explanation: While Node.js primarily runs in a single thread, it can spawn
child threads for computationally expensive tasks using the
"worker_threads" module. These worker threads can run tasks concurrently,
which can improve the performance of CPU-intensive operations. However,
these are a bit more complex to manage, as they can create conditions such
as race conditions. It's important to note that it's often better to use Node.js's
non-blocking I/O operations to handle asynchronous operations, and leave
computationally expensive tasks to be handled by systems designed to
handle such tasks.
Node.js uses _________ for its runtime.
1. Java
2. Python
3. JavaScript
4. C++

Correct Response: Option 3


Explanation: Node.js uses JavaScript for its runtime. This is because
Node.js is a platform built on the V8 JavaScript runtime. This allows
developers to write server-side scripts in JavaScript.
Node.js is built on the __________ JavaScript
engine.
1. SpiderMonkey
2. Chakra
3. JavaScriptCore
4. V8

Correct Response: Option 4


Explanation: Node.js is built on the V8 JavaScript engine. V8 is Google's
open-source high-performance JavaScript and WebAssembly engine,
written in C++. It is used in Google Chrome and also in Node.js, among
others.
____________ is the main package manager for
Node.js.
1. pip
2. npm
3. yarn
4. composer

Correct Response: Option 2


Explanation: npm (Node Package Manager) is the main package manager
for Node.js. It helps to install libraries, packages and is automatically
installed when you install Node.js.
Imagine you are building a real-time chat
application with Node.js. How would you ensure it
can handle high traffic volume without significant
delays?
1. Using HTTP/2 protocol
2. Use PHP instead of Node.js
3. Incorporating a load balancer and using the cluster module
4. Switching to WebSocket protocol

Correct Response: Option 3


Explanation: To ensure a real-time chat application with Node.js can handle
high traffic volume without significant delays, we can incorporate a load
balancer and use the cluster module in Node.js. This allows the application
to be scaled across multiple CPU cores. Besides, implementing appropriate
logging and monitoring system will also be helpful to detect and solve any
performance issues as soon as they occur.
Suppose you are working on a web application in
Node.js and the application is crashing when it
encounters an error. How might you prevent the
application from crashing upon encountering an
error?
1. Switch to another language
2. Ignore the error
3. Use a try-catch block
4. Add a domain to handle the error

Correct Response: Option 4


Explanation: To prevent a Node.js application from crashing when it
encounters an error, one effective way is to add a domain to handle the
error. Domains provide a way to handle multiple different IO operations as
a single group. It's a module that helps with handling multiple I/O
operations, grouping them together, and handling errors from them all at
once if needed.
Consider a scenario where your Node.js
application is taking too long to execute database
queries, leading to a delay in response. How would
you go about identifying and solving this
problem?
1. Ignore the problem
2. Use longer timeout durations
3. Identify slow queries and optimize them
4. Switch to a faster database

Correct Response: Option 3


Explanation: In a scenario where a Node.js application is taking too long to
execute database queries, you should first identify the slow queries. This
can be done by logging the execution time of queries or using a profiler.
Once the slow queries have been identified, you can work on optimizing
them. This could be through indexing, rewriting the queries, or adjusting
the database schema.
What command line command is used to execute a
Node.js file?
1. run
2. exec
3. node
4. execute

Correct Response: Option 3


Explanation: The command 'node' is used to execute a Node.js file. You
need to type 'node' followed by the file name in your terminal to execute a
Node.js file. For example, 'node app.js' would run the 'app.js' file.
How would you install a package globally using
npm?
1. npm install package
2. npm global install package
3. npm install -g package
4. npm install package -global

Correct Response: Option 3


Explanation: To install a package globally using npm, the command is 'npm
install -g package'. The '-g' flag in the npm install command specifies that
the package should be installed globally. This allows the package to be used
in any directory or Node.js project on your computer.
What is the purpose of the 'package.json' file in a
Node.js application?
1. To list all the images used in the application
2. To list the CSS stylesheets
3. To maintain the list of project dependencies and provide information
about the application
4. To keep track of all HTML files

Correct Response: Option 3


Explanation: The 'package.json' file in a Node.js application is used to hold
various metadata relevant to the project. This file is used to give
information to npm that allows it to identify the project as well as handle
the project's dependencies. It can also contain other metadata such as a
project description, the version of the project in a particular distribution,
license information, even configuration data - all the information needed to
install and run the project.
How can you make a Node.js application
automatically restart if it crashes or if files
change?
1. By using the Node.js 'restart' method
2. By manually restarting the application
3. By using a process manager like 'pm2' or a utility like 'nodemon'
4. By using the 'forever' module in Node.js

Correct Response: Option 3


Explanation: You can make a Node.js application automatically restart if it
crashes or if files change by using a process manager like 'pm2' or a utility
like 'nodemon'. These tools can monitor your Node.js application and
automatically restart it if it crashes or if any of the files it depends on
change.
What's the primary difference between
dependencies and devDependencies in
'package.json' file?
1. 'dependencies' are modules which are needed in production while
'devDependencies' are only needed for development
2. 'dependencies' are modules which are needed in development while
'devDependencies' are only needed for production
3. 'dependencies' are only for Node.js modules, while 'devDependencies' are
for all types of modules
4. 'dependencies' are only for third-party modules, while 'devDependencies'
are for in-house modules

Correct Response: Option 1


Explanation: In a 'package.json' file, 'dependencies' are modules which are
also needed at runtime in production, while 'devDependencies' are usually
only required during development, while you're coding or running a local
server on your machine. For example, testing tools, transpilers and bundlers
would typically be listed under 'devDependencies' because they're not
needed in production.
Can you explain the use of 'exports' and
'module.exports' in Node.js?
1. They are used to export functions for use in other files
2. They are used to export variables for use in other files
3. They are used to export both variables and functions for use in other files
4. They are used to include other JavaScript files

Correct Response: Option 3


Explanation: In Node.js, 'exports' and 'module.exports' are used to make
parts of your module (functions, objects, or primitive values) available for
external use. This can be used in other files using the 'require' function. The
difference between 'exports' and 'module.exports' gets subtle when objects
are involved. 'module.exports' should be used when you want to expose a
constructor function or a complete object from a file.
The __________ command is used to initialize a
new Node.js project and create a 'package.json'
file.
1. npm start
2. npm install
3. npm init
4. npm run

Correct Response: Option 3


Explanation: The 'npm init' command is used to initialize a new Node.js
project and create a 'package.json' file. This command will prompt you for a
number of things such as the name and version of your application. You can
simply hit RETURN to accept the default settings.
When you install packages locally, they are stored
in the __________ directory.
1. global
2. node_modules
3. npm_packages
4. local_modules

Correct Response: Option 2


Explanation: When you install packages locally using npm, they are stored
in the 'node_modules' directory. Each project has its own 'node_modules'
folder, where the dependencies are stored.
__________ is a popular tool used to automatically
restart a Node.js application when file changes in
the directory are detected.
1. pm2
2. nodemon
3. forever
4. node-restarter

Correct Response: Option 2


Explanation: 'nodemon' is a popular tool used to automatically restart a
Node.js application when file changes in the directory are detected. It is a
utility that will monitor for any changes in your source and automatically
restart your server. This can be very useful in a development environment.
Imagine you're setting up a new Node.js project.
Walk me through the steps you would take to
initialize the project and prepare it for
development.
1. Create a new directory, navigate into it, and run 'npm start'.
2. Create a new directory, navigate into it, and run 'npm init', then install
necessary packages.
3. Create a new directory, navigate into it, and run 'node app.js'.
4. Create a new directory, navigate into it, and run 'npm install'.

Correct Response: Option 2


Explanation: To set up a new Node.js project, you would typically start by
creating a new directory and navigating into it. Then, you would run 'npm
init' to initialize a new Node.js project and create a 'package.json' file. The
'package.json' file is used to keep track of your project's dependencies and
their versions. After that, you would install the necessary packages for your
project using 'npm install <package_name>'.
If you are assigned to debug a Node.js application
that keeps crashing at unpredictable intervals,
how would you approach this task?
1. Restart the application repeatedly until it stops crashing.
2. Write a script to automatically restart the application whenever it crashes.
3. Use console.log statements to print out information before the application
crashes.
4. Use built-in debugging tools, logging and monitoring systems, or third-
party services like 'node-inspector' or 'debug' module to diagnose the issue.

Correct Response: Option 4


Explanation: When debugging a Node.js application that keeps crashing at
unpredictable intervals, it is best to use built-in debugging tools, logging
and monitoring systems, or third-party services like 'node-inspector' or
'debug' module to diagnose the issue. Observing the behavior of the
application, looking at the logs and setting breakpoints in the code could
help you understand what's happening before the application crashes. It is
also a good practice to have proper error handling mechanisms in the
application to prevent uncaught exceptions that could lead to application
crashes.
Let's say you've developed a Node.js application
locally and now you need to deploy it to a
production server. What steps would you need to
take?
1. Just copy and paste your application's files from your local machine to
the server.
2. Use FTP to upload your application to the server.
3. Compress your application into a single file, then extract it on the server.
4. Set up the environment on the server, upload your application, install
dependencies, set environment variables, and start your application.

Correct Response: Option 4


Explanation: When you need to deploy a Node.js application to a
production server, the process involves multiple steps: 1. Set up the
production environment: This usually involves setting up a server, getting
Node.js installed on it, and setting up any databases or other services your
application needs to run. 2. Upload your application: You can use Git, FTP,
or SCP to upload your application to the server. 3. Install dependencies:
Navigate to your project directory and run 'npm install' to install your
project's dependencies. 4. Set environment variables: Set any necessary
environment variables in your production environment. This often includes
database connection details and the Node.js environment variable
'NODE_ENV' to 'production'. 5. Start your application: Finally, you can
start your application, often using a process manager like 'pm2' to keep your
application running in the background and start it up if the server reboots.
What is the primary function of the 'require'
function in Node.js?
1. It requires the computer to run Node.js
2. It imports a Node.js module into the current file
3. It requires the user to input a value
4. It checks if Node.js is installed on the system

Correct Response: Option 2


Explanation: The 'require' function is used to import a module into the
current file. This allows the use of functions and objects from that module.
The 'require' function is a built-in function in Node.js and is a part of its
module system.
How would you define a module in Node.js?
1. As a JavaScript function
2. As a JSON object
3. As a JavaScript file
4. As an HTML file

Correct Response: Option 3


Explanation: A module in Node.js is defined as a JavaScript file. Each file
in Node.js is its own module. The module encapsulates related code into a
single unit of code which can be used in other parts of an application
isolated from the other units. This approach follows the principle of
separation of concerns in software design.
What's the purpose of 'module.exports' in
Node.js?
1. It exports a function or object from a module so it can be used in other
modules
2. It exports a JSON object from a module
3. It exports a HTML file from a module
4. It exports a CSS file from a module

Correct Response: Option 1


Explanation: In Node.js, 'module.exports' is used to export a function,
object, or value from a module so it can be used in other modules. When
another file in your Node.js application needs to use the functionality
defined in a module, it can use 'require' to import that functionality, which
was exported with 'module.exports'.
How does Node.js handle multiple 'require' calls
for the same module?
1. It loads the module multiple times
2. It loads the module once and caches it
3. It ignores all 'require' calls after the first one
4. It throws an error

Correct Response: Option 2


Explanation: When a module is required multiple times in Node.js, it
doesn't load the module multiple times. Instead, Node.js loads the module
once and caches it for future 'require' calls. This increases the efficiency of
your application and avoids potential issues with reinitializing a module.
What are the differences between module.exports
and exports in Node.js?
1. They are the same thing
2. 'module.exports' exports an object, while 'exports' exports a function
3. 'module.exports' exports a value for a module, 'exports' is a shortcut to
'module.exports'
4. 'module.exports' exports a CSS file, 'exports' exports a JavaScript file

Correct Response: Option 3


Explanation: Both 'module.exports' and 'exports' are used to make parts of
your module (functions, objects, or primitive values) available for external
use. However, there is a slight difference between the two. 'module.exports'
is the actual object that's returned as the result of a 'require' call. 'exports' is
just an alias to 'module.exports'. If you want to expose a constructor
function or a complete object from a file, you need to add it to
'module.exports'.
Can you describe a situation where you might
need to create and use a custom module in
Node.js?
1. When you need to use built-in modules like 'http' or 'fs'
2. When you need to write code that will be reused across multiple files in
your application
3. When you need to use third-party modules like 'express' or 'lodash'
4. When you need to use HTML or CSS files in your application

Correct Response: Option 2


Explanation: Custom modules are used when you have a block of code that
you need to use in several different places in your application. By creating a
custom module, you can write the code once in the module and then import
it wherever you need it using 'require'. This can help make your code more
readable, maintainable, and testable.
In Node.js, you can use the __________ function to
include modules from external files.
1. 'import'
2. 'require'
3. 'include'
4. 'use'

Correct Response: Option 2


Explanation: The 'require' function is used in Node.js to import or include
modules from external files. It allows you to use the exported
functionalities of another module in the current module.
To make objects, functions, variables or classes
available for use in other files, they need to be
added to __________ in Node.js.
1. 'exports'
2. 'module.exports'
3. 'require'
4. 'global'

Correct Response: Option 2


Explanation: In Node.js, if you want to make certain parts of your module
(like objects, functions, variables, or classes) available for external use, you
need to add them to 'module.exports'. Other modules can then import these
using 'require'.
Node.js treats each JavaScript file as a separate
__________.
1. 'file'
2. 'folder'
3. 'module'
4. 'class'

Correct Response: Option 3


Explanation: In Node.js, each JavaScript file is treated as a separate
module. This modular architecture helps in creating maintainable and
reusable code. Each module in a Node.js has its own context, so it cannot
interfere with other modules or pollute the global scope.
Imagine you're creating a web application that
has several different routes, each with different
handlers. How might you structure your modules
to keep your code clean and organized?
1. Create one module for all routes and handlers
2. Create a separate module for each route
3. Create a separate module for each handler
4. Create two modules: one for routes, one for handlers

Correct Response: Option 2


Explanation: When building a web application with several routes and
different handlers, it would be a good practice to create separate modules
for each route. This way, the code related to each route is isolated in its own
module, making the code easier to understand, maintain, and test. Each
route module can then be imported into the main application file.
If you're developing a large-scale application with
Node.js, how would you use modules to effectively
manage the codebase?
1. Put all code in a single module
2. Create a separate module for each functionality
3. Use only built-in and third-party modules
4. Use no modules at all

Correct Response: Option 2


Explanation: In a large-scale Node.js application, using modules effectively
is crucial for code management. You should create separate modules for
each distinct functionality. This modular approach makes the codebase
more organized, easier to understand, maintain, and test. It also enhances
code reuse and allows different team members to work on separate modules
simultaneously without much conflict.
Suppose you need to use a function across
multiple modules in your Node.js application.
What would be the best way to make this function
globally accessible?
1. Declare the function in each module
2. Declare the function in the global scope
3. Write the function in a separate module and import it wherever needed
4. Store the function in a database and fetch it whenever needed

Correct Response: Option 3


Explanation: The best way to make a function globally accessible across
multiple modules in a Node.js application would be to write the function in
a separate module and then export it. This exported function can then be
imported using 'require' in any module that needs it. This approach
promotes code reusability and keeps the global scope clean.
What is the primary use of the HTTP module in
Node.js?
1. For designing the user interface of a web application
2. For performing mathematical calculations
3. For making HTTP requests and building HTTP servers
4. For handling file input and output

Correct Response: Option 3


Explanation: The HTTP module in Node.js is primarily used for making
HTTP requests and building HTTP servers. It provides functionalities to
send HTTP requests to servers and receive responses, as well as to create a
server that can accept and respond to HTTP requests.
How would you create a server using the HTTP
module in Node.js?
1. By calling the 'createServer' method
2. By calling the 'newServer' method
3. By calling the 'buildServer' method
4. By calling the 'startServer' method

Correct Response: Option 1


Explanation: A server is created using the HTTP module in Node.js by
calling the 'createServer' method. This method returns an instance of
'http.Server'. It takes a request listener function that gets automatically
added to the 'request' event.
How can you handle incoming request methods
using the HTTP module in Node.js?
1. By checking the 'method' property of the request object
2. By using the 'handleMethod' function
3. By calling the 'getRequestMethod' function
4. By checking the 'method' property of the response object

Correct Response: Option 1


Explanation: Incoming request methods can be handled in Node.js by
checking the 'method' property of the request object, which is an instance of
IncomingMessage. This object is created by http.Server or
http.ClientRequest and passed as the first argument to the 'request' and
'response' events respectively.
How can you enable HTTP/2 using the HTTP
module in Node.js?
1. By calling the 'enableHttp2' method
2. By setting the 'http2' property to true
3. By importing the 'http2' module instead of 'http'
4. By using a third-party library

Correct Response: Option 3


Explanation: HTTP/2 in Node.js can be enabled by using the 'http2' module,
which is an updated, faster protocol for delivering web content. It's
important to note that the 'http2' module is not a direct replacement for the
'http' module and has a different API.
How does the HTTP module in Node.js handle
incoming request headers?
1. It ignores them
2. It includes them in the response headers
3. It includes them in the request object
4. It stores them in a database

Correct Response: Option 3


Explanation: The HTTP module in Node.js includes incoming request
headers in the request object. You can access these headers using the
'headers' property of the request object. Each header name is a lower-case
string, and its value is a string representing the header's text value.
What is the difference between the 'request' and
'response' objects in Node.js?
1. The 'request' object contains information about the incoming request, and
the 'response' object is used to send responses back to the client
2. The 'request' object is used to send requests, and the 'response' object is
used to receive responses
3. The 'request' object is used to send responses, and the 'response' object is
used to receive requests
4. There is no difference

Correct Response: Option 1


Explanation: The 'request' object in Node.js is an instance of
IncomingMessage. It's created by http.Server or http.ClientRequest and
provides information about the incoming request, such as the request
method, headers, and URL. The 'response' object, on the other hand, is used
to send responses back to the client. It's an instance of ServerResponse,
which is a writable stream.
The __________ method of the HTTP module is
used to create a new instance of the HTTP server
in Node.js.
1. 'newServer'
2. 'buildServer'
3. 'createServer'
4. 'startServer'

Correct Response: Option 3


Explanation: The 'createServer' method of the HTTP module is used to
create a new instance of the HTTP server in Node.js. This method takes a
callback function as an argument, which is called for each incoming client
request.
The __________ event of the HTTP server class is
emitted each time there is a request.
1. 'requestReceived'
2. 'request'
3. 'getRequest'
4. 'newRequest'

Correct Response: Option 2


Explanation: The 'request' event of the HTTP server class in Node.js is
emitted each time there is a request. The request listener function handles
requests from the client and sends back a response.
Node.js uses the __________ module to transfer
data over HTTP.
1. 'transfer'
2. 'http'
3. 'dataTransfer'
4. 'net'

Correct Response: Option 2


Explanation: Node.js uses the 'http' module to transfer data over HTTP. The
module provides functionalities for both HTTP client and server objects.
The server objects emit events when requests come in, and the client objects
emit events when server responses are received.
Suppose you're developing a RESTful API using
Node.js. How would you structure your endpoints
using the HTTP module to handle the four main
HTTP request methods (GET, POST, PUT,
DELETE)?
1. Create separate endpoints for each request method
2. Use a single endpoint to handle all request methods
3. Use a middleware to handle all request methods
4. Create endpoints based on the requested resource, not the request method

Correct Response: Option 4


Explanation: When developing a RESTful API, you would structure your
endpoints based on the requested resource and use the HTTP request
method to determine the action. For example, '/users' might be an endpoint
for user-related requests. A GET request to '/users' would retrieve a list of
users, a POST request would create a new user, a PUT request (usually with
an ID, like '/users/123') would update a user, and a DELETE request would
delete a user. This is in line with REST principles, which use standard
HTTP methods to perform actions on resources.
Imagine you're building a Node.js application that
needs to fetch data from a third-party API. How
would you use the HTTP module to make this
request and handle the response?
1. Send a GET request to the API and use a 'data' event handler to process
the response
2. Send a POST request to the API and use a 'response' event handler to
process the response
3. Send a GET request to the API and use a 'response' event handler to
process the response
4. Send a POST request to the API and use a 'data' event handler to process
the response

Correct Response: Option 3


Explanation: To fetch data from a third-party API, you would use the
'http.request' method to send a GET request to the API. This method returns
an instance of the 'http.ClientRequest' class. The 'response' event is emitted
when a response is received. The response object is an instance of
'http.IncomingMessage'. You can listen for the 'data' event on the response
object to process chunks of data as they are received, and the 'end' event to
know when the response has been fully received.
Consider a scenario where your Node.js
application is receiving a large number of requests
and becoming slow. How would you optimize your
server's performance to handle this increased
load?
1. Increase the server's memory capacity
2. Use a load balancer to distribute the load
3. Use a more powerful server
4. Use a CDN to cache responses

Correct Response: Option 2


Explanation: If your Node.js application is receiving a large number of
requests and becoming slow, one way to optimize its performance is by
using a load balancer to distribute the load across multiple instances of your
application. This effectively splits the incoming traffic, reducing the load on
any single instance. Additionally, you could implement caching where
appropriate, optimize database queries, or even consider using a more
efficient data structure or algorithm if the bottleneck is CPU-related.
What is the primary function of the File System
module in Node.js?
1. To manage database operations
2. To create server instances
3. To manage HTTP requests and responses
4. To read, write, and manage files

Correct Response: Option 4


Explanation: The primary function of the File System module in Node.js is
to interact with the file system on your computer. It provides methods for
reading, writing, and managing files and directories. More
info: https://nodejs.org/api/fs.html
How would you read a file using the File System
module in Node.js?
1. fs.read()
2. fs.readFile()
3. fs.openFile()
4. fs.getFile()

Correct Response: Option 2


Explanation: To read a file in Node.js, you would use the fs.readFile()
method provided by the File System module. This method is asynchronous
and reads the entire file all at once. For large files, consider using streams
(fs.createReadStream()) to read the file in chunks to reduce memory usage.
More
info: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
How can you create a new file using the File
System module in Node.js?
1. fs.createFile()
2. fs.open()
3. fs.writeFile()
4. fs.newFile()

Correct Response: Option 3


Explanation: The fs.writeFile() method is used to create a new file using the
File System module in Node.js. If the file does not exist, this method
creates the file. If the file exists, it replaces the content. More
info: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callba
ck
How would you check if a file exists without
opening it in Node.js?
1. fs.exists()
2. fs.isFile()
3. fs.pathExists()
4. fs.checkFile()

Correct Response: Option 1


Explanation: You can use the fs.exists() function in Node.js to check if a file
exists without opening it. This function is deprecated, however, and it's
recommended to use fs.stat() or fs.access() instead, both of which also do
not open the file. More
info: https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
How can you ensure that a function only runs
after a file has been completely written in
Node.js?
1. By using the fs.write() method
2. By using the fs.writeFile() method with a callback function
3. By using the fs.createWriteStream() method with an 'end' event listener
4. By using the fs.appendFile() method with a callback function

Correct Response: Option 2


Explanation: You can ensure a function only runs after a file has been
completely written in Node.js by using the fs.writeFile() method with a
callback function. The callback function is executed when the file has been
fully written and closed. More
info: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callba
ck
Can you explain the difference between
fs.readFile() and fs.createReadStream() in
Node.js?
1. fs.readFile() reads the entire file all at once while fs.createReadStream()
reads the file in chunks
2. fs.readFile() reads the file in chunks while fs.createReadStream() reads
the entire file all at once
3. fs.readFile() is asynchronous while fs.createReadStream() is synchronous
4. fs.readFile() is synchronous while fs.createReadStream() is asynchronous

Correct Response: Option 1


Explanation: fs.readFile() and fs.createReadStream() are both used for
reading files, but they do so in different ways. fs.readFile() reads the entire
file into memory all at once. It's simple to use but can be inefficient for
large files. fs.createReadStream() reads the file in chunks, making it more
memory efficient for large files. Both methods are asynchronous. More
info: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback htt
ps://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
The __________ method of the File System
module is used to read the content of a file in
Node.js.
1. readFileSync
2. writeFile
3. appendFile
4. unlink

Correct Response: Option 1


Explanation: In Node.js, the "readFileSync" method of the File System
module is used to read the content of a file. It's a blocking method that
returns the content of the specified file until it has read everything. This
means that no other operation can be performed until it completes reading
the file.
To delete a file in Node.js, you can use the
__________ method of the File System module.
1. unlink
2. appendFile
3. writeFile
4. readFileSync

Correct Response: Option 1


Explanation: To delete a file in Node.js, you can use the "unlink" method of
the File System module. This method removes the file or symbolic link
specified in the parameters. It's important to handle possible errors when
using this function, as it may throw an error if the file or link doesn't exist.
In Node.js, the __________ method of the File
System module can be used to rename a file.
1. rename
2. appendFile
3. writeFile
4. readFileSync

Correct Response: Option 1


Explanation: In Node.js, the "rename" method of the File System module
can be used to rename a file. This function needs two arguments: the current
path and name of the file, and the new path and name. This function can
also move a file from one directory to another.
Suppose you're writing a log processing system in
Node.js, where new log files are constantly being
created and old ones need to be read and then
deleted. How would you handle this using the File
System module?
1. Create a new log file every time
2. Read and delete logs using 'readFileSync' and 'unlink' methods
3. Delete old logs without reading
4. Store all logs in the database

Correct Response: Option 2


Explanation: In a log processing system in Node.js, you can use the File
System module to read and then delete the log files. To read a file, use the
'readFileSync' or 'readFile' method. Once the file has been read and
processed, you can delete it using the 'unlink' method. This way, your
system can consistently process new log files while keeping your storage
clean from old logs. You should ensure appropriate error handling while
performing these operations.
Imagine you are building an application that
allows users to upload and download files. How
would you use the File System module in this
context?
1. Store all files in a database
2. Use 'writeFile' or 'writeFileSync' for uploading and 'readFile' or
'readFileSync' for downloading files
3. Store files in the cache
4. Avoid using the File System module

Correct Response: Option 2


Explanation: In an application that allows users to upload and download
files, the File System module plays a crucial role. For file uploading, data
from the incoming file can be written to a new file in your server using
'writeFile' or 'writeFileSync' methods. For downloading, the content of the
file can be read using 'readFile' or 'readFileSync' and then sent to the client.
Make sure to handle potential errors effectively during these operations.
Consider a scenario where you need to efficiently
read a very large file in Node.js. How would you
accomplish this using the File System module?
1. Use 'readFileSync' method
2. Load the entire file into memory
3. Use a readable stream
4. Split the file into smaller files

Correct Response: Option 3


Explanation: Reading very large files can be memory-intensive if not
handled properly. A more efficient way to read large files is to use a
readable stream. The File System module in Node.js provides a method
'createReadStream' to read data from a file in a streaming manner. This way,
the file can be read piece by piece, reducing the amount of memory needed
at any given time and speeding up the process.
What is the primary use of the URL module in
Node.js?
1. For HTTP requests
2. For handling file operations
3. For working with URLs
4. For managing packages

Correct Response: Option 3


Explanation: The primary use of the URL module in Node.js is for working
with URLs. It provides utilities for URL resolution and parsing methods.
This can be used to transform URLs to and from URL objects, and to
extract different parts of a URL.
How would you parse a URL string into URL
object using the URL module in Node.js?
1. By using the parse() method
2. By using the format() method
3. By using the resolve() method
4. By using the toString() method

Correct Response: Option 1


Explanation: To parse a URL string into a URL object in Node.js, you can
use the parse() method from the URL module. The url.parse() method takes
a URL string as a parameter and returns a URL object with each part of the
URL (like protocol, path, query, etc.) as properties.
How can you construct a URL string from a URL
object using the URL module in Node.js?
1. By using the resolve() method
2. By using the toString() method
3. By using the parse() method
4. By using the format() method

Correct Response: Option 4


Explanation: To construct a URL string from a URL object using the URL
module in Node.js, you can use the format() method. This method formats a
parsed URL object back into a URL string.
How would you handle query parameters in a
URL using the URL module in Node.js?
1. By using the query property
2. By using the parse() method
3. By using the resolve() method
4. By using the format() method

Correct Response: Option 1


Explanation: Query parameters in a URL can be handled using
the query property of the URL object in Node.js. When you parse a URL
using the url.parse() method with the second argument as true,
the query property will be set to an object representing the query string
parameters.
What's the difference between the 'path' and
'pathname' properties of a URL object in Node.js?
1. 'path' includes the query string, 'pathname' does not
2. 'pathname' includes the query string, 'path' does not
3. 'path' and 'pathname' are the same
4. 'path' includes the protocol, 'pathname' does not

Correct Response: Option 1


Explanation: In a URL object in Node.js, the 'path' property includes the
entire path portion of the URL, including the query string (if any). The
'pathname' property, on the other hand, includes only the path section of the
URL, not including the query string.
Can you explain how to resolve a relative URL
using the URL module in Node.js?
1. By using the format() method
2. By using the parse() method
3. By using the resolve() method
4. By using the toString() method

Correct Response: Option 3


Explanation: In Node.js, you can resolve a relative URL using
the resolve() method from the URL module. This method takes a base URL
and a relative URL as parameters and resolves the relative URL against the
base URL as a web browser would for an anchor tag.
In Node.js, the URL module provides utilities for
URL resolution and parsing through the
__________ method.
1. resolve
2. parse
3. format
4. toString

Correct Response: Option 2


Explanation: In Node.js, the URL module provides utilities for URL
resolution and parsing through the 'parse' method. The 'parse' method
converts a URL string into a URL object, making it easier to work with
different components of the URL.
To construct a URL object from a URL string, you
use the __________ method in Node.js.
1. resolve
2. format
3. parse
4. toString

Correct Response: Option 3


Explanation: To construct a URL object from a URL string, you use the
'parse' method in Node.js. The 'parse' method takes a URL string and
returns an object that contains the different components of the URL.
The __________ method of the URL module in
Node.js is used to create a URL string from a URL
object.
1. resolve
2. format
3. parse
4. toString

Correct Response: Option 2


Explanation: The 'format' method of the URL module in Node.js is used to
create a URL string from a URL object. This method takes an object that
represents a URL and returns a URL string.
Imagine you're building a web scraper in Node.js.
How would you use the URL module to handle
and manipulate the URLs you encounter?
1. Using 'parse' to convert URLs into objects and 'format' to convert them
back to strings
2. Using 'resolve' to handle relative URLs
3. Using the 'query' property to handle query parameters
4. Using 'parse' and 'format' methods, 'resolve' to handle relative URLs, and
the 'query' property for query parameters

Correct Response: Option 4


Explanation: When building a web scraper, the URL module is very useful.
You can use the 'parse' method to convert the URLs into URL objects for
easy manipulation. The 'format' method can be used to convert the
manipulated URL objects back into URL strings. If you encounter relative
URLs, you can use the 'resolve' method to get the absolute URL. Moreover,
you can use the 'query' property of the URL object to handle query
parameters.
Suppose you're working on a Node.js application
that redirects users based on URL parameters.
How might you use the URL module to achieve
this functionality?
1. By using 'resolve' to handle redirects
2. By using 'parse' to read URL parameters and direct users accordingly
3. By using 'format' to create the redirect URLs
4. By using 'parse' to read URL parameters and 'format' to create the
redirect URLs

Correct Response: Option 4


Explanation: In a Node.js application that redirects users based on URL
parameters, you can use the URL module to parse the URL parameters
using the 'parse' method. Then, based on the parameters, you can construct
the redirect URLs using the 'format' method. This will allow you to
effectively control user navigation based on their input.
Consider a scenario where you need to construct a
complex URL with multiple query parameters in
your Node.js application. How would you use the
URL module to construct this URL?
1. By using 'resolve' to handle relative URLs
2. By using 'parse' to create a URL object and then adding the query
parameters
3. By creating a URL object manually and then using 'format' to convert it
into a URL string
4. By creating a URL object with the query parameters and then using
'format' to convert it into a URL string

Correct Response: Option 4


Explanation: If you need to construct a complex URL with multiple query
parameters in Node.js, you can use the URL module to help. You can create
a URL object and populate its properties including 'query' for query
parameters. Then, you can use the 'format' method to convert this object
into a URL string.
What is the primary function of npm in Node.js?
1. For URL parsing
2. For handling file operations
3. For managing packages
4. For making HTTP requests

Correct Response: Option 3


Explanation: The primary function of npm (Node Package Manager) in
Node.js is for managing packages. It is a package manager for the
JavaScript runtime environment Node.js. It hosts thousands of free
packages to download and use.
How would you install a package using npm in
Node.js?
1. Using npm download <package>
2. Using npm get <package>
3. Using npm install <package>
4. Using npm fetch <package>

Correct Response: Option 3


Explanation: To install a package using npm in Node.js, you can use the
command npm install <package>. The <package> represents the name of
the package you want to install.
What command would you use to update a
package installed via npm in Node.js?
1. npm upgrade <package>
2. npm install <package>
3. npm update <package>
4. npm renew <package>

Correct Response: Option 3


Explanation: To update a package installed via npm in Node.js, you can use
the command npm update <package>. The <package> represents the name
of the package you want to update.
How would you handle a situation where you need
different versions of the same package in different
parts of your Node.js application?
1. By installing one version globally and one locally
2. By using a package manager that supports version management like Yarn
3. By using npm aliases
4. By installing the package multiple times

Correct Response: Option 3


Explanation: In a situation where you need different versions of the same
package in different parts of your Node.js application, you can use npm
aliases. Aliases were introduced in npm v6.9.0 and allow you to install
different versions of the same package under different names.
Can you explain the difference between a
package-lock.json and a package.json file in a
Node.js project?
1. package-lock.json is a manual file while package.json is automatically
generated
2. package.json is a manual file while package-lock.json is automatically
generated
3. package-lock.json includes nested dependencies while package.json does
not
4. package.json includes nested dependencies while package-lock.json does
not

Correct Response: Option 3


Explanation: In a Node.js project, package.json is manually maintained and
includes a list of all the packages and their respective versions that your
project depends on. package-lock.json is automatically generated and it
includes not only the packages that your project depends on, but also their
dependencies and the exact installed version of these.
What's the difference between installing a
package locally versus globally in a Node.js
project?
1. Global packages are accessible to all projects, local packages are not
2. Local packages are accessible to all projects, global packages are not
3. There is no difference
4. Global packages are stored in the project directory, local packages are not

Correct Response: Option 1


Explanation: In a Node.js project, when you install a package locally, it is
installed and accessible only within the specific project where it was
installed. On the other hand, when you install a package globally, it is
installed system-wide (not just in your current project) and can be accessed
by all Node.js projects.
The __________ command is used to install all
packages listed in the 'package.json' file in
Node.js.
1. npm install
2. npm get
3. npm fetch
4. npm download

Correct Response: Option 1


Explanation: The npm install command is used to install all packages listed
in the 'package.json' file in Node.js. When you run this command without
any package name, npm installs all the dependencies specified in the
'package.json' file.
To uninstall a package in Node.js, you use the
__________ command in npm.
1. npm remove
2. npm delete
3. npm uninstall
4. npm erase

Correct Response: Option 3


Explanation: To uninstall a package in Node.js, you use the npm
uninstall command in npm. This command removes a package from your
node_modules directory, as well as from the dependencies in your project's
'package.json' file.
The __________ command in npm is used to list
all installed packages in a Node.js project.
1. npm list
2. npm show
3. npm display
4. npm view

Correct Response: Option 1


Explanation: The npm list command in npm is used to list all installed
packages in a Node.js project. When you run this command, npm provides a
hierarchical view of all the installed packages and their dependencies.
Imagine you are tasked with creating a new
Node.js project from scratch. Walk me through
the steps you would take to initialize the project
using npm.
1. Start with npm init, then manually add dependencies
2. Start with npm install, then manually create a 'package.json' file
3. Start with npm init, then install dependencies as needed
4. Start with npm install, then npm init

Correct Response: Option 3


Explanation: To initialize a new Node.js project using npm, you would start
by running npm init in the terminal from your project's directory. This
command will prompt you to provide information about your project (like
name, version, description, entry point, test command, git repository,
keywords, author, license), and then it will create a 'package.json' file based
on your input. After this, you can install any required dependencies
using npm install <package> which will automatically add them to your
'package.json' file.
Suppose you are building a Node.js application
and encounter a bug that you believe is coming
from a third-party package. How would you use
npm to confirm and fix this issue?
1. By uninstalling and reinstalling the package
2. By using npm outdated to check for outdated packages
3. By using npm update to update the package
4. By uninstalling the package, then using npm outdated and npm update

Correct Response: Option 4


Explanation: If you encounter a bug that you believe is coming from a
third-party package in a Node.js application, you could use npm to confirm
and fix this issue by first uninstalling the package using npm uninstall
<package>. Then, you could use npm outdated to check if there are newer
versions of the package that may have fixed the bug. If a newer version is
available, you can update the package using npm update <package>. If the
bug still persists, it might be a good idea to contact the package's
maintainers or check its documentation or source code.
Consider a scenario where you need to distribute
a Node.js library you have created. How would
you use npm to achieve this?
1. By uploading the library to the npm registry using npm publish
2. By distributing the library through GitHub
3. By creating a 'package.json' file for the library
4. By uploading the library to the npm registry using npm publish and
creating a 'package.json' file for the library

Correct Response: Option 4


Explanation: If you need to distribute a Node.js library you have created,
you would use npm to achieve this. First, you need to ensure that your
library has a 'package.json' file with all the necessary information (name,
version, main entry point, etc.). Then, you can upload your library to the
npm registry using npm publish. Once it's uploaded, anyone can install your
library using npm install <your-library>. Remember, you need to have an
account on npm and be logged in to your account in your terminal or
command prompt to publish packages.
What is the role of the EventEmitter class in
Node.js?
1. To emit events
2. To handle HTTP requests
3. To manage file system operations
4. To perform mathematical operations

Correct Response: Option 1


Explanation: The EventEmitter class is a core module in Node.js that
facilitates communication/interaction between objects in Node.js. Basically,
it is used to emit named events which are subsequently consumed by
listener functions.
How would you trigger an event using the
EventEmitter class in Node.js?
1. emitter.emit('event')
2. emitter.on('event')
3. emitter.listen('event')
4. emitter.event()

Correct Response: Option 1


Explanation: The emitter.emit('event') syntax is used to trigger an event in
the EventEmitter class in Node.js. The 'emit' function allows a specific
event to be triggered which can then be responded to using a listener.
How can you listen for an event using the
EventEmitter class in Node.js?
1. emitter.on('event', callback)
2. emitter.emit('event', callback)
3. emitter.listen('event', callback)
4. emitter.event(callback)

Correct Response: Option 1


Explanation: The emitter.on('event', callback) syntax is used to listen for an
event using the EventEmitter class in Node.js. The 'on' method is used to
register listeners for the event being emitted.
Can you explain the concept of event-driven
programming in the context of Node.js?
1. It is a programming paradigm in which the flow of the program is
determined by events
2. It is a programming style where the order of execution is determined by
user behavior
3. It is a programming concept where one thread of execution runs from the
beginning to the end
4. It is a programming style where the main program starts a number of
events, but does not specify in what order the events execute

Correct Response: Option 1


Explanation: Event-driven programming is a paradigm in which the flow of
the program is determined by events such as user actions, sensor outputs, or
messages from other programs. Node.js is inherently event-driven because
it treats events as first-class citizens and provides an event loop and
EventEmitter class to handle event-driven operations. This makes Node.js
highly scalable and efficient for handling a large number of concurrent
operations.
What is the "error" event in Node.js and how
should it be handled?
1. It is a special type of event that gets emitted in case of any error in the
application, it should be handled using the .on('error', callback) method
2. It is a type of event that gets emitted when the application crashes, it
should be handled using the .on('crash', callback) method
3. It is a type of event that gets emitted when the application slows down, it
should be handled using the .on('slow', callback) method
4. It is a type of event that gets emitted when the application runs out of
resources, it should be handled using the .on('outOfResources',
callback) method

Correct Response: Option 1


Explanation: The "error" event is a special type of event in Node.js that gets
emitted in case of any error in the application. The recommended way to
handle this event is to listen for it using the .on('error', callback) method of
the EventEmitter. The callback function then takes the error object as an
argument, allowing for error handling logic to be written. This approach
helps in making the application robust and less prone to crashing
unexpectedly.
How can you limit the number of listeners to an
event in Node.js?
1. Using the emitter.setMaxListeners(n) method
2. Using the emitter.limitListeners(n) method
3. Using the emitter.restrictListeners(n) method
4. Using the emitter.capListeners(n) method

Correct Response: Option 1


Explanation: In Node.js, you can limit the number of listeners to an event
using the emitter.setMaxListeners(n) method. This is useful to avoid
memory leaks and performance issues, as by default, a maximum of 10
listeners can be added for a particular event.
In Node.js, the __________ method is used to
trigger an event.
1. on
2. emit
3. listener
4. trigger

Correct Response: Option 2


Explanation: In Node.js, the emit method of the EventEmitter class is used
to trigger or fire an event.
To listen for an event in Node.js, you use the
__________ method of the EventEmitter class.
1. on
2. emit
3. listener
4. trigger

Correct Response: Option 1


Explanation: In Node.js, the on method of the EventEmitter class is used to
listen for an event. This method allows you to register a listener that gets
called when the event is fired.
The __________ method of the EventEmitter class
in Node.js is used to count the number of listeners
for a specific event.
1. listenerCount
2. count
3. on
4. emit

Correct Response: Option 1


Explanation: In Node.js, the listenerCount method of the EventEmitter class
is used to return the number of listeners for a specific event.
Imagine you're building a real-time dashboard
with Node.js that needs to update whenever new
data comes in. How might you use events to
achieve this functionality?
1. I would use the EventEmitter class to emit events when new data comes
in and then use listeners to update the dashboard in real time.
2. I would poll the server every few seconds for new data and update the
dashboard when new data comes in.
3. I would use the setInterval function to periodically update the dashboard.
4. I would use WebSockets to push updates to the dashboard whenever new
data comes in.

Correct Response: Option 1


Explanation: In a real-time dashboard application built with Node.js, you
can use the EventEmitter class to emit events when new data comes in. The
data could be fetched from a database or any other data source. You would
have a listener set up that listens for this event, and when the event is
emitted, the listener would be invoked, updating the dashboard with the
new data. This way, you ensure that your dashboard is updated in real-time
whenever new data comes in.
Suppose you are building a logging system in
Node.js. How would you use the EventEmitter
class to emit logs and handle them in different
parts of your application?
1. I would create an instance of the EventEmitter class and emit a 'log' event
whenever something happens in my application that needs to be logged.
Then, in different parts of my application, I would listen for the 'log' event
and handle it appropriately.
2. I would use the 'console.log' function to log events in my application.
3. I would use a third-party logging library to handle logging in my
application.
4. I would write log messages to a file using the 'fs' module.

Correct Response: Option 1


Explanation: When building a logging system in Node.js, you can use the
EventEmitter class to emit a 'log' event whenever there's something that
needs to be logged. For example, you could emit a 'log' event every time
there's a request to your server, or whenever an error occurs. In different
parts of your application, you can listen for the 'log' event and handle it
accordingly. This could include writing the log message to a file, sending it
to an external logging service, or simply printing it to the console. This
makes your logging system highly flexible and decoupled, as the code that
emits log events doesn't need to know what happens to these log messages.
Consider a scenario where you're building a
Node.js application that involves complex
workflows, such as uploading a file, processing it,
and then saving the result. How might events help
manage this workflow?
1. I would use events to break down the workflow into smaller, manageable
tasks. For instance, I could emit an 'uploadComplete' event once a file is
uploaded, then listen for this event to trigger the file processing. Once the
processing is complete, I could emit a 'processingComplete' event and listen
for it to trigger the saving of the result.
2. I would use callbacks to manage the workflow. Each step of the
workflow would be a function that takes a callback, and the callback would
be responsible for starting the next step.
3. I would use Promises to manage the workflow. Each step of the
workflow would return a Promise, and the next step would start when the
Promise resolves.
4. I would use async/await to manage the workflow. This would allow me
to write asynchronous code in a synchronous manner, making the code
easier to read and understand.

Correct Response: Option 1


Explanation: In a complex workflow like the one described, events can be
used to break down the process into smaller, more manageable tasks, and to
ensure that each step is completed before the next one starts. For example,
once a file is uploaded, an 'uploadComplete' event can be emitted. A
listener can then be set up to listen for this event and start processing the
file. Once the processing is complete, a 'processingComplete' event can be
emitted, which triggers the saving of the result. This allows each part of the
workflow to be handled independently and makes the overall process more
manageable. Moreover, by using events, the workflow becomes more
flexible and easier to modify or extend in the future.
Which module in Node.js is commonly used for
handling file uploads?
1. http
2. fs
3. multer
4. url

Correct Response: Option 3


Explanation: The multer middleware in Node.js is commonly used for
handling multipart/form-data, which is primarily used for file uploads.
How would you access uploaded files in the
request object in Node.js?
1. request.body
2. request.file
3. request.data
4. request.params

Correct Response: Option 2


Explanation: When you're using the multer middleware in Node.js for file
uploads, you can access the uploaded file from the request.file property in
your middleware function.
What is the purpose of the 'destination' function
in the 'multer' middleware in Node.js?
1. To specify the destination directory where uploaded files should be
stored.
2. To specify the destination URL where the client should be redirected
after file upload.
3. To specify the format of the destination file name.
4. To specify the maximum file size for uploads.

Correct Response: Option 1


Explanation: The 'destination' function in the 'multer' middleware is used to
determine within which folder the uploaded files should be stored.
How would you handle multiple file uploads in a
single request using Node.js?
1. Using the multer.array() function.
2. Using the multer.fields() function.
3. Using the multer.multiple() function.
4. Using the multer.upload() function.

Correct Response: Option 1


Explanation: The multer.array() function is used when you want to handle
multiple uploaded files from a single field in the form. This function takes
the name of the field and the maximum number of files allowed.
Can you explain how to limit the size of uploaded
files in Node.js?
1. By setting the 'maxSize' option in the 'multer' middleware.
2. By checking the 'size' property of the uploaded file and rejecting if it's
too large.
3. By using the 'fs.stat' function to get the size of the uploaded file and
rejecting if it's too large.
4. By setting the 'limit' option in the 'multer' middleware.

Correct Response: Option 1


Explanation: In the multer middleware, you can limit the size of uploaded
files by setting the 'limits' option in the storage configuration. For
example, limits: { fileSize: maxSize } where maxSize is the maximum size
in bytes.
How would you handle the upload of files with
different MIME types in Node.js?
1. By checking the 'mimetype' property of the uploaded file and handling it
accordingly.
2. By using the 'multer.mimetype()' function to get the MIME type of the
uploaded file.
3. By using the 'fs.stat' function to get the MIME type of the uploaded file.
4. By setting the 'mimetype' option in the 'multer' middleware.

Correct Response: Option 1


Explanation: When a file is uploaded using the multer middleware, you can
access the MIME type of the file from the 'mimetype' property of
the file object. You can then handle the file differently based on its MIME
type. For example, you might want to handle images differently from text
files or PDFs.
In Node.js, the __________ middleware is often
used to handle multipart/form-data, which is
primarily used for file upload.
1. multer
2. http
3. fs
4. url

Correct Response: Option 1


Explanation: The multer middleware in Node.js is commonly used for
handling multipart/form-data, which is primarily used for file upload. Learn
more at: https://www.npmjs.com/package/multer
The __________ function of the multer
middleware in Node.js is used to handle the file
data during an upload.
1. .single()
2. .array()
3. .multer()
4. .upload()

Correct Response: Option 1


Explanation: The .single() function of the multer middleware in Node.js is
used to handle the file data during an upload. The argument to .single() is
the name of the form field in the upload request. Learn more
at: https://www.npmjs.com/package/multer
The __________ configuration option in multer
allows you to restrict the type of files that can be
uploaded.
1. fileFilter
2. limits
3. storage
4. destination

Correct Response: Option 1


Explanation: The fileFilter configuration option in multer allows you to
restrict the type of files that can be uploaded. It provides a function where
you can test the file information and decide whether to accept the file.
Learn more at: https://www.npmjs.com/package/multer
Imagine you're building a Node.js application that
allows users to upload profile pictures. How would
you handle the file upload and ensure only valid
image files are accepted?
1. Use multer with a fileFilter that checks the file type
2. Use the 'fs' module to check the file type after upload
3. Use the 'http' module to check the file type in the request
4. Use the 'url' module to check the file type in the URL

Correct Response: Option 1


Explanation: When handling profile picture uploads, one approach would
be to use the multer middleware for handling the file uploads. To ensure
only valid image files are accepted, you could use the fileFilter option to
restrict the file types that can be uploaded. This function gets the file
information and you can decide whether to accept the file based on its
MIME type. Learn more at: https://www.npmjs.com/package/multer
Suppose you are developing a content
management system where users can upload
various types of documents (e.g., PDFs, DOCX,
PPT). How would you handle the file upload
process?
1. Use multer and configure it to accept different file types
2. Use the 'fs' module to handle file uploads
3. Use the 'http' module to handle file uploads
4. Use the 'url' module to handle file uploads

Correct Response: Option 1


Explanation: In this scenario, you could use the multer middleware for
handling the file uploads. You might want to use the fileFilter option to
restrict the file types that can be uploaded to those that are supported by
your system. The fileFilter function gets the file information and you can
decide whether to accept the file based on its MIME type. Learn more
at: https://www.npmjs.com/package/multer
Consider a scenario where your Node.js
application needs to accept large file uploads, but
you want to prevent your server from being
overwhelmed with too much data at once. How
would you manage this?
1. Use multer and set a limit on the file size
2. Use the 'fs' module to split the file into chunks
3. Use the 'http' module to handle the file upload in stages
4. Use the 'url' module to handle the file upload

Correct Response: Option 1


Explanation: In this scenario, you could use the multer middleware for
handling the file uploads and set a limit on the file size to prevent your
server from being overwhelmed. This could be done using the limits option
in the multer configuration. Learn more
at: https://www.npmjs.com/package/multer
Which Node.js module is commonly used to send
emails?
1. Nodemailer
2. http
3. fs
4. url

Correct Response: Option 1


Explanation: Nodemailer is a module for Node.js that makes it easy to send
emails from your server. It supports various transports, and has wide
compatibility with many different email service providers. Learn more
at: https://nodemailer.com/about/
How do you configure an SMTP server using
Nodemailer in Node.js?
1. By defining the SMTP transport
2. By defining the HTTP transport
3. By using the fs module
4. By using the url module

Correct Response: Option 1


Explanation: To configure an SMTP server using Nodemailer in Node.js,
you define the SMTP transport. This typically includes the server's host
name, port, and authentication details. Learn more
at: https://nodemailer.com/smtp/
How can you send an email with an attachment
using Node.js?
1. By using the attachments property in the mail options
2. By using the url module
3. By using the fs module
4. By using the http module

Correct Response: Option 1


Explanation: You can send an email with an attachment using Node.js and
Nodemailer by using the 'attachments' property in the mail options. This
property takes an array of attachment configuration objects, with each
object specifying the content, filename, and other properties of the
attachment. Learn more at: https://nodemailer.com/message/attachments/
How would you handle a situation where you need
to send a large number of emails at once using
Node.js?
1. Using Nodemailer's bulk mailing capabilities
2. By sending each email separately
3. By using the fs module
4. By using the url module

Correct Response: Option 1


Explanation: If you need to send a large number of emails at once using
Node.js, you could take advantage of Nodemailer's bulk mailing
capabilities. Nodemailer allows you to send an email to multiple recipients,
or you can use a mailing solution like Nodemailer's 'SMTP Pool' transport
for managing a pool of SMTP connections. Learn more
at: https://nodemailer.com/smtp/pooled/
Can you explain how to send an HTML formatted
email in Node.js?
1. By specifying the HTML content in the html property of the mail options
2. By using the fs module
3. By using the http module
4. By using the url module

Correct Response: Option 1


Explanation: You can send an HTML formatted email in Node.js and
Nodemailer by specifying the HTML content in the 'html' property of the
mail options. The HTML content will be sent as the body of the email, and
clients that support HTML will display it accordingly. Learn more
at: https://nodemailer.com/message/
How would you configure Nodemailer to use a
third-party SMTP service like Gmail or SendGrid
in Node.js?
1. By defining the SMTP transport with the service's host name, port, and
authentication details
2. By using the fs module
3. By using the http module
4. By using the url module

Correct Response: Option 1


Explanation: To configure Nodemailer to use a third-party SMTP service
like Gmail or SendGrid in Node.js, you would define the SMTP transport
with the service's host name, port, and authentication details. Some services
may require additional setup or specific settings. Learn more
at: https://nodemailer.com/smtp/well-known/
In Node.js, the __________ module is often used to
send emails.
1. Nodemailer
2. http
3. fs
4. url

Correct Response: Option 1


Explanation: Nodemailer is a module for Node.js applications that allows
for easy email sending. It has a simple API and supports various transports
and many different email service providers. Learn more
at: https://nodemailer.com/about/
To send an email in Node.js, you can use the
__________ method of the Nodemailer's
transporter object.
1. sendMail
2. listen
3. readFile
4. write

Correct Response: Option 1


Explanation: The sendMail method of the Nodemailer's transporter object is
used to send emails. It takes an options object containing email information
(e.g., from, to, subject, text) and a callback function that will be executed
once the email has been sent or an error has occurred. Learn more
at: https://nodemailer.com/usage/
The __________ configuration option in
Nodemailer allows you to specify the SMTP server
that should be used to send the email.
1. host
2. route
3. path
4. directory

Correct Response: Option 1


Explanation: The host configuration option in Nodemailer allows you to
specify the SMTP server that should be used to send the email. It is part of
the transport configuration object, which also includes other SMTP server
details such as port and authentication. Learn more
at: https://nodemailer.com/smtp/
Imagine you're building a Node.js application that
sends a confirmation email whenever a user
creates an account. How would you implement
this using Nodemailer?
1. Set up a Nodemailer transporter, configure it with your SMTP server
details, and use the sendMail method in the user account creation handler to
send the confirmation email.
2. I would use the fs module.
3. I would use the http module.
4. I would use the url module.

Correct Response: Option 1


Explanation: In order to send a confirmation email when a user creates an
account, you would set up a Nodemailer transporter with your SMTP server
details. In your user account creation handler, after the account is
successfully created, you would use the sendMail method of the transporter
to send the confirmation email. The email details (such as from, to, subject,
and text or html) would be provided in the options object passed to
sendMail. Learn more at: https://nodemailer.com/usage/
Suppose you are developing a system in Node.js
that sends weekly newsletters to subscribers. How
would you handle sending these emails?
1. I would use Nodemailer in combination with a job scheduler like node-
cron to send the newsletters at weekly intervals.
2. I would use the fs module.
3. I would use the http module.
4. I would use the url module.

Correct Response: Option 1


Explanation: In a scenario where you need to send weekly newsletters to
subscribers, you could use Nodemailer in combination with a job scheduler
like node-cron. Node-cron allows you to schedule tasks in Node.js using
cron syntax. You could schedule a job that runs every week and uses
Nodemailer's sendMail method to send the newsletters to all subscribers.
Learn more at: https://www.npmjs.com/package/node-cron
Consider a scenario where you need to send an
email with multiple attachments and a complex,
custom-designed layout. How would you handle
this using Node.js?
1. I would use Nodemailer's attachments option to attach multiple files, and
the html option to design a complex layout for the email.
2. I would use the fs module.
3. I would use the http module.
4. I would use the url module.

Correct Response: Option 1


Explanation: If you need to send an email with multiple attachments and a
complex, custom-designed layout using Node.js, you can use Nodemailer's
attachments option to attach multiple files, and the html option to design a
complex layout for the email. The attachments option accepts an array of
attachment objects, and the html option accepts a string of HTML content.
Learn more
at: https://nodemailer.com/message/attachments/ and https://nodemailer.co
m/message/
In Node.js, the __________ built-in module
provides a way of scheduling tasks.
1. timer
2. http
3. fs
4. url

Correct Response: Option 1


Explanation: The timer module in Node.js provides functions to schedule
tasks to be executed at some time in the future. It includes methods like
setTimeout, setInterval, and setImmediate.
To read and write files in Node.js, you would use
the __________ built-in module.
1. fs
2. http
3. path
4. url

Correct Response: Option 1


Explanation: The 'fs' (File System) module in Node.js is used to perform
file operations. It provides functions for reading from and writing to files
synchronously as well as asynchronously.
The __________ built-in module in Node.js is used
to handle events.
1. events
2. http
3. fs
4. url

Correct Response: Option 1


Explanation: The 'events' module in Node.js allows for the handling of
events. The 'events' module provides the 'EventEmitter' class, which is used
to raise and handle events.
Suppose you're building a Node.js application that
needs to consume a large CSV file, process each
line, and then write the result to a new file. How
would you use built-in Node.js modules to
accomplish this task efficiently?
1. I would use the 'fs' module to read and write files, 'readline' to read the
CSV file line by line, and 'stream' to handle data in chunks.
2. I would use the 'url' module.
3. I would use the 'http' module.
4. I would use the 'path' module.

Correct Response: Option 1


Explanation: To consume a large CSV file, process each line, and then write
the result to a new file efficiently, the 'fs' (File System) module can be used
to read from and write to files, the 'readline' module can be used to read the
CSV file line by line, and the 'stream' module can be used to handle data in
chunks, which is more memory-efficient than loading the entire file into
memory.
Imagine you're developing a secure Node.js
application that needs to store user passwords.
How would you use Node.js's built-in modules to
hash and salt the passwords?
1. I would use the 'crypto' module to generate a salt and hash the password.
2. I would use the 'fs' module.
3. I would use the 'http' module.
4. I would use the 'url' module.

Correct Response: Option 1


Explanation: The 'crypto' module in Node.js provides cryptographic
functionality that includes a set of wrappers for OpenSSL's hash, HMAC,
cipher, decipher, sign, and verify functions. For storing passwords, you
could use this module to generate a random salt and a hash of the password
and salt. The salt and hash would be stored instead of the actual password
for security reasons.
What is a first class function in JavaScript?
1. A function that is written before all other functions
2. A function that runs first when code is executed
3. A function that can be assigned to a variable, passed as an argument or
returned from other functions
4. A function that is part of the JavaScript core library

Correct Response: Option 3


Explanation: In JavaScript, functions are first-class objects. This means that
functions can be passed as arguments to other functions, returned by other
functions, and assigned to variables. This is a key aspect of the language's
expressiveness and is fundamental to many aspects of its functional
programming nature.
What is Node.js and how it works?
1. A browser-based programming language
2. A Java-based server-side platform
3. A JavaScript runtime built on Chrome's V8 JavaScript engine
4. A CSS preprocessor

Correct Response: Option 3


Explanation: Node.js is a JavaScript runtime built on Chrome's V8
JavaScript engine. It allows the execution of JavaScript independently from
a browser. It works by compiling JavaScript to machine code at runtime
using the V8 JavaScript engine. It is mainly used to build network programs
like web servers. It is single-threaded and uses a concurrency model based
on an event loop.
How do you manage packages in your Node.js
project?
1. Using the "import" keyword
2. Using the Node Package Manager (npm)
3. Using a .zip file
4. Using a .txt file

Correct Response: Option 2


Explanation: In Node.js, packages are managed using the Node Package
Manager, also known as npm. npm is the default package manager for
Node.js and allows developers to install, update, and manage packages from
the npm registry. It also manages dependencies for an application.
How is Node.js better than other frameworks
most popularly used?
1. Node.js is a language, not a framework
2. Node.js can be used in any type of application
3. Node.js is not necessarily better, it depends on the use case
4. Node.js is better because it has more users

Correct Response: Option 3


Explanation: Whether Node.js is "better" than other frameworks or not is
highly dependent on the use case. Node.js is particularly well-suited to
building scalable, high-performance web applications due to its non-
blocking, event-driven architecture. However, other frameworks may be
better suited for different types of projects. Factors such as the needs of the
project, the team's familiarity with the language and framework, and the
requirements for performance and scalability all play into the decision of
which framework to use.
Explain the steps how “Control Flow” controls the
functions calls?
1. Control flow is not related to function calls
2. Control flow determines the order in which functions are called
3. Control flow controls function calls by calling each function one after the
other
4. Control flow controls function calls by executing all functions at the
same time

Correct Response: Option 2


Explanation: The control flow is the order in which the computer executes
statements in a script. Control flow means that when you read a script, you
must not only read from start to finish but also take into account conditional
statements, loops, function calls, etc. This becomes especially important in
asynchronous programming (like in Node.js) where callbacks, promises,
async/await are used to handle tasks outside of the main thread.
What are the advantages of using promises
instead of callbacks?
1. Promises make it easier to handle exceptions
2. Promises allow for cleaner, more readable code
3. Promises enable better control over asynchronous tasks
4. All of the above

Correct Response: Option 4


Explanation: Promises offer several advantages over callbacks in
JavaScript. They enable better control over asynchronous tasks, allow for
cleaner and more readable code, and make it easier to handle exceptions. In
addition, promises have methods like .then, .catch, and .finally that make it
easier to sequence asynchronous operations and handle errors.
What is fork in Node.js?
1. A Git command
2. A method to spawn a new process in Node.js
3. A tool for running multiple versions of Node.js
4. A function for duplicating objects

Correct Response: Option 2


Explanation: In Node.js, fork is a method in the child_process module
which is used to spawn a new Node.js process. The newly created process
will have a new V8 instance, and operates independently of the parent
process. However, a communication channel is established allowing
messages to be passed between the parent and child.
Why is Node.js single-threaded?
1. Because JavaScript is single-threaded
2. Because it's easier to write code that way
3. Because multi-threading is not needed for web development
4. Because Node.js is not capable of multi-threading

Correct Response: Option 1


Explanation: Node.js is single-threaded because it's built on JavaScript,
which is single-threaded. This is because JavaScript was originally
designed to run in the browser, where the single-threaded model simplifies
the programming model and avoids issues with concurrency. However,
Node.js does use multiple threads internally, for example for I/O operations,
via libuv library. The main event loop, where your JavaScript code runs, is
single-threaded.
How do you create a simple server in Node.js that
returns Hello World?
1. Using the Express.js framework
2. Using the http.createServer method
3. Using a third-party library
4. Node.js does not support creating servers

Correct Response: Option 2


Explanation: To create a simple server in Node.js that returns 'Hello World',
you would typically use the http.createServer method provided by Node.js's
built-in HTTP module. When a request is received, the server can respond
with 'Hello World'. Here's a simple example: const http = require('http');
const server = http.createServer((req, res) => { res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); });
server.listen(3000, '127.0.0.1', () => { console.log('Server running at
http://127.0.0.1:3000/'); });
How many types of API functions are there in
Node.js?
1. One
2. Two
3. Three
4. Four

Correct Response: Option 2


Explanation: There are two types of API functions in Node.js:
Asynchronous, Non-blocking functions and Synchronous, Blocking
functions. Asynchronous functions do not block the program flow and
allow other operations to continue before they complete. On the other hand,
synchronous functions block other operations until they complete.
What is REPL?
1. A Node.js package
2. A JavaScript task runner
3. Read-Eval-Print-Loop
4. A type of variable

Correct Response: Option 3


Explanation: REPL stands for Read-Eval-Print-Loop. It is an interactive
shell that processes Node.js expressions. The shell reads JavaScript code
the user enters, evaluates the result of interpreting the line of code, prints
the result to the user, and loops until the user leaves the session. It's a quick
and easy way to test JavaScript snippets.
List down the two arguments that async.queue
takes as input?
1. Function and Callback
2. Task function and Concurrency value
3. Error and Callback
4. Task and Error

Correct Response: Option 2


Explanation: The async.queue method in the Async utility module takes
two arguments as input: 1) Task function: The function to be applied to
each item in the queue. 2) Concurrency value: An integer for determining
how many task functions should be processed concurrently.
What is the purpose of module.exports?
1. To export functions to be used in other files
2. To export variables to be used globally
3. To import modules from other files
4. To create new modules in Node.js

Correct Response: Option 1


Explanation: The purpose of module.exports is to export functions, objects
or values from a file so they can be required and used in other files. When
creating a module in Node.js, anything assigned to module.exports will be
exposed as the public interface when the module is required in another file.
What tools can be used to assure consistent code
style?
1. ESLint
2. Prettier
3. JSHint
4. All of the above

Correct Response: Option 1,2,3,4


Explanation: Tools such as ESLint, Prettier, and JSHint can be used to
assure consistent code style. ESLint checks your JavaScript code for errors,
Prettier automatically formats your code according to specified rules, and
JSHint checks your JavaScript code for errors and potential problems. All
of these tools help in maintaining a consistent coding style across your
project.
What is Event Driven Programming? Explain
with respect to Node.js.
1. Programming that is driven by events such as user actions
2. Programming that is driven by changes in the state of the program
3. Programming that is driven by a sequence of operations
4. Programming that is driven by the programmer's instructions

Correct Response: Option 1


Explanation: Event Driven Programming is a programming paradigm in
which the flow of the program is determined by events such as user actions,
sensor outputs, or messages from other programs. In the context of Node.js,
this means that Node.js waits for events to happen and responds to them,
instead of following a linear sequence of operations. This is why Node.js is
so well-suited for handling asynchronous operations and building scalable
network applications.
What is the difference between asynchronous and
synchronous execution in Node.js?
1. Synchronous execution happens all at once, while asynchronous
execution happens in sequence
2. Synchronous execution blocks the execution of subsequent operations
until the current operation completes, while asynchronous execution allows
other operations to continue running in the background
3. Synchronous execution allows other operations to continue running in the
background, while asynchronous execution blocks the execution of
subsequent operations until the current operation completes
4. There is no difference between synchronous and asynchronous execution

Correct Response: Option 2


Explanation: In Node.js, synchronous execution refers to line-by-line
execution, meaning it will execute each line of code one by one, hence if a
line of code takes time to fetch the result then the next line of code will
have to wait until the previous line has completed execution. On the other
hand, asynchronous execution means that the code will execute all lines of
code at once, so it will not wait for any function to complete.
What is the purpose of using Express.js with
Node.js?
1. To make it easier to write HTML
2. To extend the functionality of Node.js
3. To add support for Python
4. To create better visual designs

Correct Response: Option 2


Explanation: Express.js is a web application framework for Node.js. Its
main purpose when used with Node.js is to provide tools and features to
simplify the process of building complex web applications. Express.js helps
to manage routes, requests, and views along with beautiful API handling. It
also has a rich ecosystem of middleware, which allows developers to add
extra functionality to their web applications.
How does error handling work in Node.js?
1. Errors are always caught and handled by the global error handler
2. Errors can be handled using callbacks, events, and middleware
3. Errors are automatically logged and do not need to be handled
4. Errors are always handled by try-catch blocks

Correct Response: Option 2


Explanation: Error handling in Node.js can be done using several methods
including callbacks, events, and middleware. For asynchronous code, errors
are usually handled through callbacks, often in the form of an "error-first"
callback, where the first argument is an error object. If the operation was
successful, this object will be null, and meaningful results of the operation
will follow. For events, especially when dealing with streams, errors can be
handled by listening for the 'error' event. Express.js, a popular framework in
Node.js, uses middleware to handle errors. This involves passing errors to
the next() function and then handling them in a special error-handling
middleware.
How can you avoid callback hell in Node.js?
1. By using a single callback for all asynchronous operations
2. By using third-party libraries
3. By using techniques such as modularization, Promises, async/await
4. By ignoring errors in callbacks

Correct Response: Option 3


Explanation: Callback hell, also known as the pyramid of doom, refers to
heavily nested callbacks that can become hard to read and maintain. In
Node.js, you can avoid callback hell by modularizing the code into smaller,
independent functions, using control flow libraries, or by using Promises
and the async/await syntax, which are built into the language. Promises and
async/await in particular provide a way to write asynchronous code that can
be structured as if it were synchronous, making it much easier to read and
understand.
How is data read from a file in Node.js?
1. Using the 'readFile' method of the fs module
2. By opening the file in a text editor
3. By sending a GET request to the file's URL
4. Node.js cannot read data from files

Correct Response: Option 1


Explanation: In Node.js, data can be read from a file using the 'readFile' or
'readFileSync' method of the fs (file system) module. The 'readFile' method
is asynchronous and takes a callback function to handle the data once it's
ready, while 'readFileSync' is a synchronous operation that blocks the event
loop until it's done. An example of reading file with 'readFile' would
be: fs.readFile('/path/to/file', 'utf8' , (err, data) => { if (err) {
console.error(err); return; } console.log(data); })
What is npm and why is it used in Node.js
projects?
1. npm is a coding style guide for Node.js
2. npm is a type of database used in Node.js
3. npm is a version control system for Node.js
4. npm is a package manager for Node.js

Correct Response: Option 4


Explanation: npm stands for Node Package Manager. It is used in Node.js
projects to install and manage dependencies, which are packages of code
that your project uses. npm allows developers to easily manage and update
these dependencies, and also makes it easy to share and reuse code with
other developers. npm provides access to a registry of over 800,000 open
source projects, and is a crucial tool for modern JavaScript development.
How can you debug an application in Node.js?
1. By using console.log() statements
2. By using a debugger such as the built-in Node.js debugger or a third-
party tool like Visual Studio Code
3. By reading the source code line by line
4. By asking other developers for help

Correct Response: Option 2


Explanation: Debugging a Node.js application can be done in several ways.
One method is by using the built-in Node.js debugger. You can also use
external tools such as Visual Studio Code or WebStorm, which have
excellent debugging support. Another common debugging technique is to
use console.log() statements to print out the values of variables at different
points in your code. However, using a debugger can provide a more
interactive debugging experience, allowing you to step through your code
line by line, inspect variables, and pause your code on specific lines.
How do you handle exceptions in Node.js?
1. By using try-catch blocks
2. By using promises and async/await
3. By using error-first callbacks
4. All of the above

Correct Response: Option 4


Explanation: Exceptions in Node.js can be handled in several ways. For
synchronous code, you can use try-catch blocks. For asynchronous code,
you can use error-first callbacks, where the first argument of the callback
function is reserved for an error object. If the asynchronous operation was
successful, the error object will be null, and the results of the operation will
follow. If an error occurred, the error object will contain details about the
error. With Promises and async/await, you can use .catch() method to
handle any errors that occurred in a promise chain, or you can use try-catch
blocks in an async function to handle errors.
What is the significance of package.json in
Node.js?
1. It contains the list of all the files in your Node.js project
2. It is a file that contains metadata about your Node.js project and its
dependencies
3. It is a file that contains your Node.js source code
4. It is a configuration file for your text editor

Correct Response: Option 2


Explanation: The package.json file in a Node.js project is extremely
important. It holds various metadata relevant to the project. This file is used
to give information to npm that allows it to identify the project as well as
handle the project's dependencies. It can also contain other metadata such as
a project description, the version of the project in a particular distribution,
license information, even configuration data - all of which can be crucial to
both npm and to the end users of the package.
How is Node.js non-blocking?
1. Node.js runs all operations in parallel
2. Node.js pauses the execution of functions that take a long time to
complete
3. Node.js uses a single-threaded event loop model to handle multiple
concurrent clients
4. Node.js uses multiple threads to handle multiple clients

Correct Response: Option 3


Explanation: Node.js is non-blocking because it uses a single-threaded,
event-driven architecture for its operation. This means that it can handle
multiple operations concurrently without waiting for previous operations to
complete. This is made possible through the use of asynchronous functions
for operations that take a long time to complete, such as reading from the
file system, accessing a database, or retrieving data from the internet. When
Node.js starts a time-consuming task, it sets up a callback function and then
continues to run the rest of your program. When the task is complete,
Node.js runs the callback function to handle the result, allowing it to handle
multiple clients with a single thread.
What is the Event Loop in Node.js?
1. It is a loop that emits events in Node.js
2. It is a loop that waits for events and dispatches them to event handlers
3. It is a loop that listens for events and handles them
4. It is a loop that runs forever and blocks the rest of your code from
running

Correct Response: Option 2


Explanation: The event loop is a mechanism in Node.js that waits for and
dispatches events or messages in a program. It works by making a request
and then allowing other code to run while it waits for the response. The
event loop allows Node.js to perform non-blocking I/O operations, even
though JavaScript is single-threaded, by offloading operations to the system
kernel whenever possible. When the operations are done, the system kernel
tells Node.js so that the appropriate callback may be added to the poll queue
to eventually be executed.
How do you update a dependency using npm?
1. By changing the version number in package.json and running 'npm
update'
2. By deleting the dependency and re-adding it
3. By running 'npm install [package]'
4. By running 'npm update [package]'

Correct Response: Option 4


Explanation: Updating a dependency in a Node.js project using npm can be
done by running 'npm update [package]'. If you want to update all
dependencies to their latest versions, you can simply run 'npm update'
without specifying a package. Note that this will only update minor and
patch versions because npm respects semantic versioning. To update to a
new major version, you would need to use a different command or update
the version number in your package.json file.
How do you create a child process in Node.js?
1. By using the 'fork' method of the 'process' module
2. By using the 'spawn' or 'exec' methods of the 'child_process' module
3. By creating a new instance of the 'Process' class
4. By calling the 'createChildProcess' function with a function argument

Correct Response: Option 2


Explanation: In Node.js, you can create a new child process by using the
'spawn' or 'exec' methods of the 'child_process' module. The 'spawn' method
launches a new process with a given command, while 'exec' spawns a shell
and runs a command within that shell, buffering any generated output. Both
methods return a ChildProcess instance, which is an EventEmitter that
emits an event when the process finishes.
What is the purpose of process.nextTick() in
Node.js?
1. It schedules a callback function to be invoked in the next iteration of the
event loop
2. It schedules a callback function to be invoked after a certain number of
milliseconds
3. It schedules a callback function to be invoked in the next tick of the
system clock
4. It schedules a callback function to be invoked immediately

Correct Response: Option 1


Explanation: The purpose of process.nextTick() in Node.js is to schedule a
callback function to be invoked in the next iteration of the event loop, after
the current operation completes. This is different from setImmediate(),
which schedules a callback to be invoked on the next cycle of the event
loop, allowing any I/O operations to be processed first. process.nextTick()
is a way to allow functions to run asynchronously, but as soon as possible,
rather than being placed at the end of the call stack.
What is the difference between setImmediate()
and setTimeout()?
1. setTimeout() executes a function after a certain amount of time, while
setImmediate() executes a function immediately
2. setImmediate() executes a function after a certain amount of time, while
setTimeout() executes a function immediately
3. setImmediate() is used in browser-based JavaScript, while setTimeout()
is used in Node.js
4. There is no difference between setImmediate() and setTimeout()

Correct Response: Option 1


Explanation: In Node.js, setTimeout() schedules a function to be called after
a certain number of milliseconds. It can be used to delay execution of a
function. On the other hand, setImmediate() is used to schedule a function
to be called as soon as possible but after the current operation completes
and any I/O events in the current event loop iteration. This means that if it's
placed within an I/O cycle, it will execute before setTimeout() and
setInterval().
How do you use 'this' keyword in Node.js?
1. It is used to refer to the current function
2. It is used to refer to the current module
3. It is used to refer to the global object
4. It is used to refer to the object that a function is a method of

Correct Response: Option 4


Explanation: The 'this' keyword in Node.js works similarly to how it does in
most object-oriented programming languages. It refers to the object that a
function is a method of. However, in the global scope, 'this' refers to the
global object, and in a function (unless it's an arrow function), 'this' refers to
the global object, not the function itself. 'this' can be a tricky concept in
JavaScript and Node.js because its value is determined by how a function is
called, not where the function is defined.
Explain how 'Cluster' module in Node.js works.
1. It allows you to create child processes that all share the same server port
2. It allows you to balance load across multiple CPU cores
3. It allows you to manage a cluster of Node.js servers
4. It allows you to schedule tasks to be run at specific times

Correct Response: Option 1


Explanation: The cluster module in Node.js is a way to create child
processes, but with the added feature of enabling these processes to share
server ports. This allows your Node.js application to take advantage of
multi-core systems, thereby increasing performance and reliability. Each
child, when forked, runs on its own thread and has its own memory space,
but they can share server handles and use IPC (Inter-Process
Communication) to communicate with the master process. This makes it
possible to handle more client requests, increasing your application's
capacity and reliability.
What are the global objects in Node.js?
1. Global objects are variables that are available everywhere in your code
2. Global objects are objects that are part of the global scope
3. Global objects are objects that are part of the window object
4. Global objects are objects that are part of the process object

Correct Response: Option 2


Explanation: Global objects in Node.js are objects that are available in all
modules. They're part of the global scope, meaning they can be accessed
from anywhere in your code without having to require them. Examples of
global objects include the process and console objects, and global functions
like setTimeout and setImmediate. Note that unlike in a browser
environment, global variables defined with 'var' in Node.js are not added to
the global object. They're only global to the module they're defined in.
Explain the concept of middleware in Express.js.
1. Middleware is software that connects different parts of an Express
application
2. Middleware is software that is run before the final request handler
3. Middleware is software that handles errors in an Express application
4. Middleware is software that manages the database in an Express
application

Correct Response: Option 2


Explanation: Middleware in Express.js refers to functions that have access
to the request object (req), the response object (res), and the next function in
the application’s request-response cycle. These functions can execute any
code, make changes to the request and the response objects, end the
request-response cycle, or call the next function in the stack. In other words,
middleware functions are functions that have the signature (req, res, next).
They are used to modify req and res objects for tasks like parsing request
bodies, adding headers, handling errors, or anything that needs to be done
before the final request handler is called.
What is a Buffer in Node.js and when is it used?
1. A Buffer is a type of data structure used to store data
2. A Buffer is a temporary storage spot for data being transferred from one
place to another
3. A Buffer is a type of variable used to store binary data
4. A Buffer is a method used to delay the execution of a function

Correct Response: Option 2


Explanation: A Buffer in Node.js is a global class that provides a way to
work with different kinds of binary data. It is mainly used to store binary
data, while reading from a file or receiving packets over the network. When
dealing with TCP streams or the file system, it's necessary to handle octets
of data. Node.js provides the Buffer object which is stored outside the V8
heap and is an array of integers, each representing a byte of data. It's
particularly useful when dealing with data streams - reading or writing
to/from the file system, or transferring data over the network, or for any
operations where you are working with binary data.
What are streams in Node.js and why are they
used?
1. Streams are a way to handle reading/writing files, network
communications, or any kind of end-to-end information exchange
2. Streams are a type of data type in JavaScript
3. Streams are used to implement event-driven programming in Node.js
4. Streams are a way to handle HTTP requests in Node.js

Correct Response: Option 1


Explanation: Streams in Node.js are objects that let you read data from a
source or write data to a destination in a continuous way. Streams are
especially useful when dealing with large amounts of data, as they allow
you to read or write data piece by piece, instead of all at once, reducing
memory footprint and increasing efficiency. Streams can be readable,
writable, or both. They are instances of EventEmitter, so they can emit
events that our application can listen to and respond.
How can you secure a Node.js application?
1. By implementing authentication and authorization
2. By using HTTPS and avoiding vulnerable dependencies
3. By validating and sanitizing inputs
4. All of the above

Correct Response: Option 4


Explanation: Securing a Node.js application involves multiple practices.
You should implement authentication and authorization to ensure only
authorized users have access to certain resources. Use HTTPS to encrypt
data in transit. Validate and sanitize all inputs to protect against attacks such
as XSS (Cross Site Scripting) and SQL injection. Regularly update
dependencies and make sure no dependencies have known vulnerabilities.
Use secure HTTP headers to protect from various types of attacks. Limit the
rate of requests to protect against brute-force attacks. These are just some
examples, and security needs can vary greatly depending on the specifics of
the application.
Explain the differences between 'throw' and 'emit'
in Node.js.
1. 'throw' is used for exceptions while 'emit' is used for events
2. 'throw' is used for events while 'emit' is used for exceptions
3. 'throw' is used to create errors while 'emit' is used to handle them
4. 'throw' and 'emit' are synonyms and do the same thing

Correct Response: Option 1


Explanation: In Node.js, 'throw' is used to throw exceptions. When an
exception is thrown, the normal flow of control is halted and the control is
transferred to the nearest exception handler. 'emit', on the other hand, is
used to trigger events. In Node.js, events are an important aspect of the
programming model. The 'emit' method is a part of the EventEmmitter class
and is used to trigger events which can then be listened to and handled by
event handlers. While they both can be used in error handling, their
purposes are quite different.
How do you scale a Node.js application?
1. By using the cluster module
2. By using load balancers
3. By breaking the application into microservices
4. All of the above

Correct Response: Option 4


Explanation: Scaling a Node.js application can be done in several ways.
The cluster module in Node.js allows for the creation of child processes that
all share server ports, enabling load balancing over multiple CPU cores.
Load balancers can also be used to distribute incoming network traffic
across multiple servers, thus distributing the load. Additionally, a Node.js
application can be broken down into microservices, which are
independently deployable services that do one thing well. Each
microservice can be scaled independently to meet demand for that specific
part of the application.
What are the different types of HTTP requests
that Node.js can handle?
1. GET, POST, PUT, DELETE
2. POST, GET, SET, DELETE
3. POST, PUT, DELETE, HEAD
4. GET, POST, PUT, UPDATE

Correct Response: Option 1


Explanation: Node.js can handle various types of HTTP requests including
GET, POST, PUT, DELETE. Each type of request serves a different
purpose. GET is used to request data from a server, POST is used to send
data to a server, PUT is used to update a resource on a server, and DELETE
is used to delete a resource from a server.
How do you create a RESTful API in Node.js?
1. By using the Express.js framework and defining route handlers
2. By using the HTTP module in Node.js
3. By using the request module in Node.js
4. By using the fs module in Node.js

Correct Response: Option 1


Explanation: Creating a RESTful API in Node.js is often done by using the
Express.js framework. Express allows you to define route handlers for
various HTTP requests, and these routes can correspond to the operations
defined by a RESTful API. For example, a GET request to '/users' might
return a list of users, a POST request to '/users' could create a new user, a
PUT request to '/users/:id' might update a user, and a DELETE request to
'/users/:id' could delete a user. Each route handler will contain the logic for
handling that specific request.
What is the difference between Node.js and Ajax?
1. Node.js is a runtime environment for executing JavaScript code server-
side, and AJAX is a client-side technique for creating asynchronous web
applications
2. AJAX is a server-side technology and Node.js is used on the client side
3. Node.js and AJAX are the same thing
4. Node.js is a technique for creating asynchronous web applications, and
AJAX is a JavaScript runtime

Correct Response: Option 1


Explanation: Node.js and AJAX both deal with asynchronous operations,
but in different contexts. Node.js is a JavaScript runtime environment that
allows you to execute JavaScript code server-side, opening up the ability to
interact with the file system, databases, and more. AJAX, or Asynchronous
JavaScript and XML, is a client-side technique that allows you to make
asynchronous HTTP requests to a server, without requiring a full page
refresh. AJAX can be used within a Node.js application, but they serve
different purposes.
What are the tasks that should be done
asynchronously in Node.js?
1. File system operations, Database operations, Network requests
2. Console logging
3. Simple mathematical operations
4. All of the above

Correct Response: Option 1


Explanation: In Node.js, tasks that take a long time to complete or that
would otherwise block the event loop should be done asynchronously. This
includes things like reading or writing to the file system, querying a
database, or making network requests. These tasks are often performed
asynchronously to prevent blocking the main thread, which could result in
poor performance.
How to connect Node.js application with
MongoDB?
1. By using a MongoDB driver or an ORM like Mongoose
2. By using the 'fs' module in Node.js
3. By using the 'http' module in Node.js
4. By using AJAX calls

Correct Response: Option 1


Explanation: Connecting a Node.js application to MongoDB can be
achieved by using a MongoDB driver, which provides methods to interact
with MongoDB databases. A popular choice is the Mongoose library, which
provides a straightforward, schema-based approach to modeling your
application data and includes built-in type casting, validation, and query
building. It's as simple as defining your schema, and using methods
provided by the library to query the database.
How to handle file uploads in Node.js?
1. Using 'multer' middleware in an Express.js application
2. By using the 'fs' module in Node.js
3. By using 'http' module in Node.js
4. By using AJAX calls

Correct Response: Option 1


Explanation: Handling file uploads in Node.js can be accomplished using a
middleware for handling 'multipart/form-data', which is primarily used for
uploading files. One such middleware is 'multer'. It's easy to integrate with
Express.js and gives you the ability to access uploaded files from the
request object in your routes.
What is the difference between a module and a
package in Node.js?
1. A module is a single JavaScript file that has some reasonable
functionality, while a package is a directory with one or more modules
inside it and a package.json file which has metadata about the package
2. Modules are packages that are installed globally, and packages are
modules that are installed locally
3. A package is a single JavaScript file, while a module is a directory with
multiple JavaScript files
4. Modules and packages refer to the same thing in Node.js

Correct Response: Option 1


Explanation: In Node.js, a module is a single JavaScript file that has some
reasonable functionality which can be exported and used in other files. A
package, on the other hand, is a directory that consists of one or more such
modules and includes a package.json file that contains metadata about the
package. This metadata can include the package's name, version,
description, author, dependencies, and other information. Packages are how
code is distributed in Node.js via the Node Package Manager (npm).
How can you test a Node.js application?
1. By using testing libraries such as Mocha, Jest or Jasmine
2. By running the application and checking the output
3. By reading through the code to identify any errors
4. By using a linter like ESLint

Correct Response: Option 1


Explanation: Testing a Node.js application is usually done using testing
frameworks and libraries such as Mocha, Jest, or Jasmine. These
frameworks provide functions to structure your tests and make assertions.
For instance, Mocha provides describe and it functions to structure your
tests, and you can use a library like Chai for assertions. You can also use
tools like Sinon for creating spies, stubs, and mocks. For end-to-end testing,
tools like Puppeteer, Cypress, or WebDriver can be used.
How to run a function every 1 minute in Node.js?
1. Using 'setInterval' function
2. Using 'setTimeout' function
3. Using 'fs' module
4. Using AJAX calls

Correct Response: Option 1


Explanation: The setInterval function in Node.js is used to schedule
recurring operations. To run a function every 1 minute, you would use
setInterval and specify a delay of 60,000 milliseconds (which is equivalent
to 1 minute).
What are the key differences between Node.js and
Angular.js?
1. Node.js is a JavaScript runtime used for server-side programming while
Angular.js is a JavaScript framework used for client-side (browser)
programming
2. Node.js and Angular.js are the same thing
3. Node.js is used for frontend development while Angular.js is used for
backend development
4. Node.js is a JavaScript framework while Angular.js is a JavaScript
runtime

Correct Response: Option 1


Explanation: Node.js is a JavaScript runtime environment that allows you to
execute JavaScript on the server side. It's often used for building back-end
services like APIs. Angular.js, on the other hand, is a JavaScript framework
developed by Google for building dynamic, single-page client-side
applications. So, in simple terms, Node.js is used for server-side
programming while Angular.js is used for client-side programming.
What do you understand by callback hell?
1. It refers to a situation where callbacks are nested within callbacks,
making the code hard to read and debug
2. It is an error that occurs in Node.js when a callback function is not
defined
3. It refers to the error that occurs when a callback function takes a long
time to return a result
4. It is a type of callback function in Node.js

Correct Response: Option 1


Explanation: Callback hell, also known as the pyramid of doom, refers to a
situation where callbacks are nested within other callbacks, making the
code hard to read, understand, and debug. It is a phenomenon that afflicts
JavaScript developers when they try to execute multiple asynchronous
operations one after the other. Various techniques can be used to avoid or
alleviate callback hell, such as modularization, using promises, or using
async/await.
What is an event-loop in Node JS?
1. It is the entity that handles external events and converts them into
callback invocations
2. It is a JavaScript loop that runs in the Node.js runtime
3. It is a type of loop that occurs when an event occurs
4. It is a loop that runs indefinitely in a Node.js application

Correct Response: Option 1


Explanation: The event loop is a mechanism in Node.js that handles
external events and converts them into callback invocations. It allows
Node.js to perform non-blocking I/O operations, despite JavaScript being
single-threaded, by offloading operations to the system kernel whenever
possible.
If Node.js is single threaded then how does it
handle concurrency?
1. Node.js uses event-driven programming and a non-blocking I/O model
which allows it to handle multiple concurrent operations
2. Node.js creates a new thread for every client request
3. Node.js does not support concurrency
4. Node.js uses multi-threading to handle concurrency

Correct Response: Option 1


Explanation: Even though JavaScript is single-threaded, Node.js can still
handle concurrency through the use of events and callbacks. Node.js uses
an event-driven, non-blocking I/O model. When a Node.js application
needs to perform an I/O operation, like reading from the network, accessing
a database or the filesystem, instead of blocking the thread and wasting
CPU cycles waiting, it will initiate the operation and then continue to
execute other code. When the operation completes, it receives the results
through a callback function, which gets pushed onto the event loop to be
executed later.
Differentiate between process.nextTick() and
setImmediate()?
1. process.nextTick() defers the execution of an action till the next pass
around the event loop and setImmediate() executes a callback on the next
cycle of the event loop
2. process.nextTick() and setImmediate() do the same thing
3. setImmediate() defers the execution of an action till the next pass around
the event loop and process.nextTick() executes a callback on the next cycle
of the event loop
4. process.nextTick() and setImmediate() are used for error handling in
Node.js

Correct Response: Option 1


Explanation: In Node.js, process.nextTick() and setImmediate() are used to
schedule callbacks to be called in the next iteration of the Event Loop.
However, they behave slightly differently. process.nextTick() defers the
execution of an action till the next pass around the event loop or it simply
calls the callback function once the ongoing execution of the event loop is
finished. setImmediate() is designed to execute a script once the current poll
(event loop) phase completes. In other words, it executes a callback on the
next cycle of the event loop.
How does Node.js overcome the problem of
blocking of I/O operations?
1. By using a single-threaded event loop model
2. By using multi-threading
3. By running each I/O operation in a separate process
4. By using Ajax calls

Correct Response: Option 1


Explanation: Node.js overcomes the problem of blocking I/O operations by
using an event-driven, non-blocking I/O model. This means that Node.js
can initiate I/O operations and then continue executing other code. When
the I/O operation completes, its callback function is added to the event loop
for execution. This model allows Node.js to handle many concurrent
connections efficiently, making it well-suited for scalable network
applications. More info: https://nodejs.dev/learn/the-nodejs-event-loop
How can we use async await in node.js?
1. By declaring a function with 'async' keyword and then using the 'await'
keyword inside it
2. By declaring a function with 'await' keyword and then using the 'async'
keyword inside it
3. By using the 'promise' keyword
4. By using the 'callback' keyword

Correct Response: Option 1


Explanation: The async/await feature in Node.js is used to handle
asynchronous operations and it makes asynchronous code look like
synchronous code. An async function is declared using the 'async' keyword
before the function name. Inside an async function, the 'await' keyword is
used before a Promise to make JavaScript wait until the Promise settles, and
then return its result. This approach leads to cleaner and more readable
code. More info: https://nodejs.dev/learn/modern-asynchronous-javascript-
with-async-and-await
What are node.js streams?
1. Streams are objects that let you read data from a source or write data to a
destination in a continuous manner
2. Streams are a type of data type in Node.js
3. Streams are a type of function in Node.js
4. Streams are a type of loop in Node.js

Correct Response: Option 1


Explanation: Streams in Node.js are objects that let you read data from a
source or write data to a destination in a continuous manner. They are
especially useful when dealing with large amounts of data because you
don't have to wait for all the data to be available to start processing it.
Streams can help to improve the performance and efficiency of your
Node.js applications. More info: https://nodejs.dev/learn/nodejs-streams
What are node.js buffers?
1. Buffers are temporary storage spots for raw data
2. Buffers are a type of variable in Node.js
3. Buffers are a type of function in Node.js
4. Buffers are a type of loop in Node.js

Correct Response: Option 1


Explanation: Buffers in Node.js are used to represent binary data in the
form of a sequence of bytes. They are typically used when you need to read
data from a file or a network connection, or when you need to work with an
image, or with other kinds of data that are not text. Buffers can be converted
to other data types and can also be encoded to various formats like Base64,
Hex, and others. More info: https://nodejs.dev/learn/nodejs-buffers
What is middleware?
1. Middleware functions are functions that have access to the request object
(req), the response object (res), and the next middleware function in the
application’s request-response cycle
2. Middleware is a type of database in Node.js
3. Middleware is a type of function that runs only once in a Node.js
application
4. Middleware is a type of variable in Node.js

Correct Response: Option 1


Explanation: Middleware functions in Node.js are functions that have
access to the request object (req), the response object (res), and the next
middleware function in the application’s request-response cycle. They can
execute any code, make changes to the request and response objects, end
the request-response cycle, or call the next middleware function in the
stack. Middleware functions are very important in managing the request-
response cycle in frameworks like Express.js. More
info: https://expressjs.com/en/guide/using-middleware.html
Explain what a Reactor Pattern in Node.js?
1. The reactor pattern is a design pattern that allows non-blocking I/O
operations by using events and callbacks
2. The reactor pattern is a pattern used in React.js for rendering components
3. The reactor pattern is a type of loop in Node.js
4. The reactor pattern is a type of function in Node.js

Correct Response: Option 1


Explanation: The reactor pattern is a design pattern used in Node.js to
handle multiple concurrent I/O operations. This pattern allows Node.js to
perform non-blocking I/O operations by using a loop that's called an event
loop along with a callback mechanism. When an I/O request is made, a
callback function is registered. Node.js continues executing the rest of its
program and will not wait for the I/O operation to complete. Once the I/O
operation is finished, the callback function is put into the event loop to be
executed. More info: https://nodejs.dev/learn/the-nodejs-event-loop
Why should you separate Express app and
server?
1. To keep the application modular and easier to test
2. To reduce the size of the application
3. To improve the performance of the application
4. To make the application compatible with other programming languages

Correct Response: Option 1


Explanation: Separating the Express app from the server leads to a more
modular codebase. This makes it easier to test and debug the application.
When the server setup is separate, you can require the Express application
in your tests and listen to requests on a different port, avoiding conflicts
with the running application. This decoupling also makes it easier to deploy
the application in different environments. More
info: https://stackoverflow.com/questions/23281895/whats-the-point-of-
separating-app-and-server-in-express-js
For Node.js, why Google uses V8 engine?
1. Because it is fast and has a great performance for I/O bound tasks
2. Because it is written in JavaScript
3. Because it supports multi-threading
4. Because it is compatible with all operating systems

Correct Response: Option 1


Explanation: The V8 engine, developed by Google, is used in Node.js
because it's very fast. It compiles JavaScript into machine code before
execution rather than interpreting it in real-time. V8 also handles memory
allocation/de-allocation for objects and it garbage collects objects it no
longer needs. These features make it highly suitable for the event-driven,
non-blocking model of Node.js. More
info: https://www.journaldev.com/7462/node-js-google-v8-engine-example
Describe the exit codes of Node.js?
1. Exit codes are used to indicate the termination cause of a process
2. Exit codes are a type of error in Node.js
3. Exit codes are used to start a Node.js process
4. Exit codes are a type of function in Node.js

Correct Response: Option 1


Explanation: Exit codes in Node.js are used to indicate why a process was
terminated. There are several exit codes, each with its own specific
meaning. For example, exit code 0 means the process completed
successfully, while exit code 1 means there was an uncaught fatal
exception. Exit codes are an important part of Node.js' error handling
mechanism and they can be used to debug issues with your application.
More info: https://nodejs.org/api/process.html#process_exit_codes
Explain the concept of stub in Node.js?
1. A stub is a piece of code used to stand in for some other programming
functionality
2. A stub is a type of error in Node.js
3. A stub is a function that runs only once in a Node.js application
4. A stub is a type of variable in Node.js

Correct Response: Option 1


Explanation: Stubs in Node.js (and generally in programming) are pieces of
code that stand in for other programming functionality. They are used in
testing to simulate the behavior of some code in a controlled way. For
example, you might use a stub to simulate a function that makes a network
request so you can test how your code handles the response from that
request. More info: https://sinonjs.org/releases/latest/stubs/
What are some practical uses of the 'util' module
in Node.js?
1. It's used for debugging and printing formatted console messages,
inspecting objects, etc.
2. It's used for handling HTTP requests
3. It's used for creating servers in Node.js
4. It's used for reading and writing data to the file system

Correct Response: Option 1


Explanation: The 'util' module is a core Node.js module packed with
utilities. It provides several utility functions useful for debugging, such as
'util.inspect' for inspecting JavaScript objects and 'util.format' for formatting
strings. It also has functions for deprecating APIs, inheriting properties of
objects, and other useful tasks. More info: https://nodejs.org/api/util.html
How do you handle uncaught exceptions in
Node.js?
1. By using 'process.on("uncaughtException")' to listen for the
'uncaughtException' event
2. By using try/catch blocks
3. By using callbacks
4. By using promises

Correct Response: Option 1


Explanation: Uncaught exceptions in Node.js can be caught at the process
level by attaching a handler for 'uncaughtException' event. However,
'uncaughtException' is a very crude mechanism for exception handling and
should be used sparingly. It's often better to use domain modules for
handling multiple route handlers and servers, or promises for asynchronous
error handling. Regardless, it's generally considered best practice to shut
down and restart the process after 'uncaughtException' to avoid potential
undetermined state of the application. More
info: https://nodejs.org/api/process.html#process_event_uncaughtexception
Explain the use of a buffer class in Node.js.
1. Buffer class provides instances to store raw data similar to an array of
integers but corresponds to a raw memory allocation outside the V8 heap
2. Buffer class is used for dealing with TCP streams
3. Buffer class is used for executing system commands in Node.js
4. Buffer class is used to create and manage child processes

Correct Response: Option 1


Explanation: Buffer class in Node.js is used to handle binary data. Each
buffer corresponds to some raw memory allocated outside V8. Buffers act
somewhat like arrays of integers, but aren't resizable and have a whole
bunch of methods specifically for binary data. In addition, they are used to
represent a fixed-sized chunk of memory which can be manipulated via an
API. They are particularly useful when dealing with TCP streams or the file
system. More info: https://nodejs.org/api/buffer.html
How does garbage collection work in Node.js?
1. Node.js uses the V8's built-in garbage collector, which uses the concept
of 'reachability' as a criterion for whether objects are needed
2. Node.js uses manual garbage collection
3. Garbage collection in Node.js is done by periodically stopping the
program and looking for unused objects
4. Node.js does not use garbage collection

Correct Response: Option 1


Explanation: Node.js is built on the V8 JavaScript engine, which has a
built-in garbage collector. The garbage collector's job is to track memory
allocation and identify when a piece of allocated memory is no longer
needed and free it. The main concept used by the garbage collector to
identify 'garbage' is 'reachability'. This refers to the possibility of accessing
a piece of data by any means from the root (i.e., global object). If an object
is unreachable, it is considered garbage and will be collected. More
info: https://v8.dev/blog/trash-talk
How would you go about handling sessions in
Node.js?
1. You can use middleware like express-session for session handling
2. Sessions are not supported in Node.js
3. Session handling can only be done using cookies in Node.js
4. Node.js automatically handles sessions

Correct Response: Option 1


Explanation: To handle sessions in Node.js, you can use middleware such
as express-session. Express-session can store session data on the server; it
writes a cookie on the client's browser to store the session id, and, during
the subsequent request, uses this id to look up session information on the
server. More info: https://www.npmjs.com/package/express-session
What is the role of REPL in Node.js?
1. REPL (Read Eval Print Loop) is an interactive shell that processes
Node.js expressions
2. REPL is used to compile Node.js code
3. REPL is a type of function in Node.js
4. REPL is used to log errors in Node.js

Correct Response: Option 1


Explanation: REPL stands for Read-Eval-Print Loop. It represents a
computer environment like a Windows console or Unix/Linux shell where a
command is entered and the system responds with an output. Node.js comes
with a built-in REPL, which performs the following tasks: Read - Reads
user's input, parse the input into JavaScript data-structure, and stores in
memory. Eval - Takes and evaluates the data structure. Print - Prints the
result. Loop - Loops the above command until the user presses ctrl-c twice.
More info: https://nodejs.org/api/repl.html
How can a child process be spawned in Node.js?
1. Node.js has the child_process module that allows us to create child
processes
2. Child processes cannot be spawned in Node.js
3. Child processes are spawned using the http module in Node.js
4. Child processes in Node.js can only be created using third-party libraries

Correct Response: Option 1


Explanation: Node.js provides the 'child_process' module which is used to
spawn child processes. The 'child_process.spawn' method spawns a new
process with the given command, with command line arguments in args. If
omitted, args defaults to an empty array. It returns a stream with 'stdout' and
'stderr'. The 'child_process' module enables us to access Operating System
functionalities by running any system command inside a, well, child
process. More info: https://nodejs.org/api/child_process.html
How can you use middleware in Express.js for
logging requests?
1. Middleware functions in Express.js have access to the request object
(req), the response object (res), and the next function. You can create a
middleware function to log details of each request
2. Middleware in Express.js cannot be used for logging
3. Only third-party middleware can be used for logging in Express.js
4. Middleware in Express.js can only be used to handle errors

Correct Response: Option 1


Explanation: Middleware functions in Express.js have access to the request
object (req), the response object (res), and the next function in the
application’s request-response cycle. By creating a middleware function and
placing it before routes are defined, you can access details of each request
and log necessary details. This could be done using third-party middleware
like morgan or by creating a custom middleware function. More
info: https://expressjs.com/en/guide/writing-middleware.html
What are the differences between 'readFile' and
'createReadStream' in Node.js?
1. 'readFile' reads the entire file at once, while 'createReadStream' reads the
file piece by piece, handling the data in chunks
2. 'readFile' can only read text files, while 'createReadStream' can handle
any file format
3. 'readFile' and 'createReadStream' have no differences
4. 'readFile' is a synchronous function while 'createReadStream' is
asynchronous

Correct Response: Option 1


Explanation: 'readFile' is a method that reads the entire file into memory
before making it available to the user, while 'createReadStream' creates a
stream that reads the file piece by piece, buffering the contents into
memory. This makes 'createReadStream' more memory efficient,
particularly for large files. More info: https://nodejs.org/api/fs.html
What is an error-first callback in Node.js, and
why is it used?
1. It is a standard in Node.js callbacks where the first argument of the
callback function is reserved for an error object
2. Error-first callbacks are used to handle errors in Node.js scripts
3. Error-first callbacks allow the program to continue executing despite
encountering an error
4. Node.js does not use error-first callbacks

Correct Response: Option 1


Explanation: The error-first callback (also known as Node-style callback) is
a convention used in Node.js where callback functions are passed an Error
object as the first argument. If there is no error, the first argument will be
null. The reason for this pattern is to make error handling more
straightforward and consistent. It allows developers to handle errors at a
higher level without the need to write error handling code everywhere.
More info: https://nodejs.org/api/errors.html#errors_error_first_callbacks
How is a Promise different from a callback?
1. Promises are a more modern, powerful, and flexible method of handling
asynchronous operations compared to callbacks
2. Promises and callbacks serve the same purpose and have no differences
3. Callbacks are a newer feature than Promises in JavaScript
4. Promises are only used for handling errors, while callbacks are used for
any type of asynchronous operation

Correct Response: Option 1


Explanation: Promises are an evolution of callbacks. They provide a more
powerful and flexible abstraction for handling asynchronous operations.
Unlike callbacks, promises are returned by the function that performs the
asynchronous operation. They provide '.then' and '.catch' methods to handle
the completion or failure of the asynchronous operation. Promises can be
chained and can handle complex asynchronous code more cleanly than
callbacks. More info: https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Using_promises
What is the purpose of the 'EventEmitter' class in
Node.js?
1. 'EventEmitter' is used to emit named events which can be consumed by
event listeners
2. 'EventEmitter' is used to create HTTP servers in Node.js
3. 'EventEmitter' is used to handle errors in Node.js applications
4. 'EventEmitter' is a module for handling file I/O

Correct Response: Option 1


Explanation: The 'EventEmitter' class in Node.js is used for handling
events. An event can be emitted, and any number of listeners can listen and
react to the event. The 'EventEmitter' class is at the core of Node.js
asynchronous event-driven architecture. Many of Node's built-in modules
inherit from 'EventEmitter', making it a fundamental concept in Node.js.
More info: https://nodejs.org/api/events.html
How do you use the 'cluster' module to create a
child process?
1. The 'cluster' module in Node.js allows you to create child processes
(workers), which share server ports with the main Node process
2. The 'cluster' module cannot be used to create child processes
3. The 'cluster' module is used to create HTTP servers in Node.js
4. The 'cluster' module is a third-party module that must be installed using
npm

Correct Response: Option 1


Explanation: The 'cluster' module in Node.js is a way to create child
processes (workers). Workers are spawned using the 'fork' method, and
these child processes can share server ports with the main Node process
(master). The 'cluster' module allows easy creation of child processes that
all share server ports. This is a key method for scaling in Node.js. More
info: https://nodejs.org/api/cluster.html
How do you avoid callback hell or pyramid of
doom in Node.js?
1. Callback hell can be avoided by using Promises, async/await, or
modularization of code
2. Callback hell can only be avoided by using third-party libraries
3. Callback hell cannot be avoided in Node.js
4. Callback hell is an outdated concept that no longer exists in modern
Node.js

Correct Response: Option 1


Explanation: Callback hell, or pyramid of doom, refers to heavily nested
callbacks that make the code hard to read and debug. This can be avoided
by several methods. You can use Promises, which is a modern feature that
simplifies async code. You can also use async/await, which makes
asynchronous code look like synchronous code. Another method is to break
callbacks into smaller functions and modules, which makes your code more
manageable. More info: https://nodejs.dev/learn/understanding-javascript-
promises
How do you secure an API built on Node.js?
1. There are many ways to secure a Node.js API, including using HTTPS,
validating input data, protecting against Cross-Site Scripting (XSS) and
SQL injection attacks, and using security headers
2. APIs in Node.js are automatically secure
3. Node.js APIs can only be secured by using HTTPS
4. API security is not a concern when using Node.js

Correct Response: Option 1


Explanation: Securing an API in Node.js involves a number of best
practices: using HTTPS, validating and sanitizing input data to protect
against SQL injection and Cross-Site Scripting (XSS) attacks, using
security headers to protect from attacks, setting cookie flags to prevent
attacks on client sessions, rate limiting API requests to prevent brute-force
attacks, and keeping your dependencies up to date to avoid potential
vulnerabilities. More info: https://expressjs.com/en/advanced/best-practice-
security.html
What is the purpose of the --save flag in the npm
install command?
1. The --save flag was used in npm versions less than 5.0 to include the
installed package into the dependencies section of your package.json
automatically
2. The --save flag is used to save the package into the devDependencies
section of your package.json
3. The --save flag is required for installing packages globally
4. There is no such flag in npm

Correct Response: Option 1


Explanation: Prior to npm 5.0, the --save flag was used to include the
installed package into the dependencies section of your package.json file
automatically. This flag is not needed after npm 5.0 as it happens by
default. More info: https://docs.npmjs.com/cli/v6/using-npm/config#save
What are some strategies to improve performance
in a Node.js application?
1. Use the cluster module
2. Use gzip compression
3. Optimize database operations
4. Avoid synchronous code in your application

Correct Response: Option 1,2,3,4


Explanation: There are several ways to improve performance in a Node.js
application: Use the cluster module to take advantage of multi-core
systems. Compress your responses with gzip to reduce the size of the data
that's being transferred. Optimize database operations, use indexes, limit the
result set size etc. Avoid synchronous code, it will block the event loop and
stall all other operations. More info: https://www.sitepoint.com/5-ways-to-
make-your-node-js-web-app-faster/
How does Node.js handle child threads?
1. Node.js primarily operates on a single thread, but for handling CPU-
intensive tasks, it can take advantage of multi-threading via the
'worker_threads' module
2. Node.js does not support multi-threading
3. Node.js operates only on multi-threads
4. Node.js spawns a new thread for every new request

Correct Response: Option 1


Explanation: Node.js primarily operates on a single thread, the event loop
which handles all asynchronous I/O operations. For CPU intensive tasks,
Node.js provides the 'worker_threads' module to spawn new threads. Each
thread is independent and does not share memory, they communicate via
message passing. More info: https://nodejs.org/api/worker_threads.html
What is the difference between a Promise and an
Observable in Node.js?
1. Promises handle a single event, while Observables can handle a sequence
of events
2. Promises are used for synchronous code, while Observables are used for
asynchronous code
3. Observables are an older feature than Promises in JavaScript
4. Promises and Observables have no differences

Correct Response: Option 1


Explanation: Promises are used for single asynchronous operations that will
resolve at some point in the future, either resolving to a value (fulfilled) or
rejecting with an error. Observables, which come from the RxJS library, are
a collection of items over time. You can think of an Observable like a
stream which can emit multiple values over time, and can be manipulated
using various operators (map, filter, etc). More
info: https://rxjs.dev/guide/overview
What is the use of DNS module in Node.js?
1. The DNS module in Node.js is used to perform domain name resolution
2. The DNS module is used to create HTTP servers
3. The DNS module is used to write to the file system
4. The DNS module is used for error handling in Node.js

Correct Response: Option 1


Explanation: The DNS module in Node.js is used to perform domain name
resolution and other DNS operations, like reverse DNS lookups. It provides
an asynchronous network wrapper and can be used to convert domain
names into IP addresses and vice versa. More
info: https://nodejs.org/api/dns.html
How does Node.js support multi-processor
platforms, and what is the main advantage of it?
1. Node.js supports multi-processor platforms using the 'cluster' module
which allows forking multiple child processes from the master process
2. Node.js does not support multi-processor platforms
3. Node.js supports multi-processor platforms using the 'child_process'
module
4. Node.js can only use one processor at a time

Correct Response: Option 1


Explanation: Node.js can take advantage of multi-processor platforms using
the 'cluster' module. This module allows you to create child processes
(workers), which are all separate instances of the main Node process. This
allows your Node.js application to handle more load by utilizing all the
cores of the system. It's a key method for scaling in Node.js. More
info: https://nodejs.org/api/cluster.html
What is the difference between 'fork', 'spawn',
and 'exec' in Node.js?
1. 'fork' is used to spawn a new Node.js process, 'spawn' launches a new
process with a given command, and 'exec' spawns a shell and runs a
command within that shell
2. All three commands are used for creating child processes, but they are
interchangeable and there are no differences between them
3. 'fork', 'spawn', and 'exec' are used for file operations in Node.js
4. nan

Correct Response: Option 1


Explanation: In Node.js, 'fork' is a special case of 'spawn' that runs a new
instance of the Node.js runtime environment and executes a specific
module. 'spawn' launches a new process with a given command. 'exec', on
the other hand, spawns a shell and runs a command within that shell,
buffering any generated output. More
info: https://nodejs.org/api/child_process.html
How do you perform error handling in a callback
function?
1. Callback functions in Node.js follow a common error-first pattern where
the first argument is reserved for an error object. If the operation was
successful, the error parameter will be null
2. Error handling in callbacks is not possible in Node.js
3. Callbacks do not require error handling
4. nan

Correct Response: Option 1


Explanation: The common pattern for error handling in Node.js callbacks is
the Error-first callback. In this pattern, the first argument of the callback
function is reserved for an error object, and the second argument is reserved
for successful response data. If the operation was successful, the error
parameter will be null, otherwise it will contain an Error object. More
info: https://nodejs.dev/learn/understanding-error-first-callbacks-in-nodejs
What are the advantages and disadvantages of
Node.js?
1. Advantage: Excellent for real-time applications
2. Disadvantage: Not suitable for CPU intensive tasks
3. Advantage: High performance and scalability
4. Disadvantage: Limited access to standard library functions

Correct Response: Option 1,2,3,4


Explanation: Node.js has several advantages such as its non-blocking I/O
model which makes it excellent for real-time applications, and its high
performance and scalability. However, it also has disadvantages: it is not
well-suited for CPU intensive tasks because incoming requests would be
blocked until the computation is done. Also, compared to other languages,
Node.js has a relatively limited access to standard library functions. More
info: https://www.geeksforgeeks.org/node-js-pros-and-cons/
What is the difference between exports and
module.exports in Node.js?
1. 'exports' is a shorthand for 'module.exports'. They point to the same
reference, but you can't change 'exports' to a new object because it won't
change 'module.exports'
2. 'exports' and 'module.exports' are used for different purposes and do not
have any relationship with each other
3. 'exports' and 'module.exports' are used for error handling in Node.js
4. nan

Correct Response: Option 1


Explanation: In Node.js, 'exports' is just a reference to 'module.exports' and
they initially point to the same empty object. They can be used
interchangeably to expose functionality from a module. However, if you
assign a new object or a function to 'exports', it doesn't change the reference
to 'module.exports'. As a result, if you want to expose a constructor function
or a new object, you should use 'module.exports'. More
info: https://www.sitepoint.com/understanding-module-exports-exports-
node-js/
How do you connect a MySQL database with
Node.js?
1. You use the 'mysql' module in Node.js to connect to a MySQL database.
The 'createConnection' method is used to create a connection to the MySQL
database server
2. Node.js cannot connect to a MySQL database
3. Connecting to a MySQL database is done through the 'fs' module in
Node.js
4. nan

Correct Response: Option 1


Explanation: To connect to a MySQL database with Node.js, you typically
use the 'mysql' module. This module provides the necessary functions to
connect to a MySQL database and execute queries. The 'createConnection'
function is used to create a connection to the MySQL database server. More
info: https://www.mysqltutorial.org/mysql-nodejs/connect/
What is 'Event Driven Programming' and how is
it used in Node.js?
1. Event Driven Programming is a programming paradigm in which the
flow of the program is determined by events such as user actions, sensor
outputs, or message passing from other programs. Node.js uses this concept
extensively in its architecture, especially with its asynchronous I/O
operations via the event loop
2. Event Driven Programming is a programming style where the flow of the
program is determined by the programmer and not by user actions or
messages from other programs
3. Node.js does not use Event Driven Programming
4. nan

Correct Response: Option 1


Explanation: Event Driven Programming is a programming paradigm where
the flow of the program is determined by events such as user actions, sensor
outputs, or messages from other programs. Node.js is inherently event-
driven because it uses events heavily in its APIs and its architecture is built
around an event loop for asynchronous I/O operations. More
info: https://nodejs.dev/learn/the-nodejs-event-loop
How can you upload files in Node.js?
1. You can use middleware like Multer in Express.js, which handles
'multipart/form-data' for uploading files
2. File uploads can only be handled by front-end JavaScript, not Node.js
3. Files are uploaded in Node.js using the 'fs' module's 'readFile' method
4. nan

Correct Response: Option 1


Explanation: To handle file uploads in Node.js, you can use middleware
such as 'multer' for Express.js applications. 'Multer' is capable of handling
'multipart/form-data', which is primarily used for file uploads. More
info: https://www.geeksforgeeks.org/upload-and-retrieve-image-on-
mongodb-using-mongoose/
Explain the purpose and functionality of package-
lock.json in a Node.js project.
1. 'package-lock.json' is automatically generated for any operations where
npm modifies either the node_modules tree or 'package.json'. It describes
the exact tree that was generated, such that subsequent installs are able to
generate identical trees, regardless of intermediate dependency updates
2. 'package-lock.json' is used to list the packages that your project depends
on. It can be updated manually by the developer
3. 'package-lock.json' is used to manage environment variables in a Node.js
project
4. nan

Correct Response: Option 1


Explanation: The 'package-lock.json' file is automatically generated for any
operations where npm modifies either the node_modules tree or
'package.json'. It describes the exact tree that was generated when installing
project dependencies, enabling subsequent installs to generate identical
trees, regardless of intermediate dependency updates. This ensures that you
get the exact same dependencies every time you install them. More
info: https://docs.npmjs.com/cli/v7/configuring-npm/package-lock-json
How does the "crypto" module work in Node.js?
1. The 'crypto' module in Node.js provides cryptographic functionality that
includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher,
sign, and verify functions
2. The 'crypto' module is used for creating server-side cookies in Node.js
3. The 'crypto' module is used for event handling in Node.js
4. nan

Correct Response: Option 1


Explanation: The 'crypto' module in Node.js provides cryptographic
functionality that includes a set of wrappers for OpenSSL's hash, HMAC,
cipher, decipher, sign, and verify functions. This module supports a wide
array of secure encryption, decryption, and hashing algorithms. More
info: https://nodejs.org/api/crypto.html
Explain how REST APIs work in Node.js.
1. REST (Representational State Transfer) APIs in Node.js work by
receiving HTTP requests (GET, POST, PUT, DELETE), and interacting
with a database or other data source to return the requested data to the client
2. REST APIs in Node.js work by storing data in the browser's localStorage
3. REST APIs in Node.js work by creating a direct link between the client
and the database
4. nan

Correct Response: Option 1


Explanation: REST (Representational State Transfer) is a software
architectural style that provides a standard for creating scalable web
services. In a RESTful web service, requests are made via HTTP to
manipulate data (usually stored in a database). These requests are made
using HTTP methods such as GET (retrieve), POST (create), PUT (update),
and DELETE (delete). Node.js can be used to build the server-side of a
REST API, with libraries like Express.js often used to simplify the process.
More info: https://www.tutorialsteacher.com/nodejs/nodejs-restful-api
What is 'callback hell'?
1. When a callback function fails to return
2. When there are too many callback functions
3. A term used for asynchronous errors
4. A scenario in which there are nested callbacks leading to unmanageable
code

Correct Response: Option 4


Explanation: 'Callback Hell' is a term used for a situation where callbacks
are nested within callbacks, making the code difficult to read and manage. It
often occurs in Node.js because JavaScript is heavily dependent on callback
functions for asynchronous operations. Techniques to mitigate 'callback
hell' include module separation, proper error handling, and using control
flow libraries or ES6's Promises and async/await.
What's new in the latest version of Node.js?
1. Stable support for ES6
2. Thread Workers in stable release
3. Stable HTTP/2 support
4. Support for TypeScript

Correct Response: Option 2


Explanation: As of my training cut-off in September 2021, one of the
significant features in the latest stable release of Node.js is Thread Workers,
which allows better CPU-intensive operations handling. However, Node.js
continuously evolves, and for the most current updates, refer to the Node.js
official website.
What is an Event Emitter in Node.js?
1. A library for creating user interfaces
2. A component for handling HTTP requests
3. A way of handling events in the browser
4. An object that triggers an event whenever a particular action occurs

Correct Response: Option 4


Explanation: In Node.js, an Event Emitter is a module that facilitates
communication/interaction between objects in Node.js. When an
EventEmitter instance experiences an error, it emits an 'error' event. When
new listeners are added, the 'newListener' event is fired, and when listeners
are removed, the 'removeListener' event is fired.
Enhancing Node.js performance through
clustering.
1. Clustering decreases the performance of Node.js applications
2. Clustering in Node.js is done using the Cluster module and it allows the
application to run parallel processes
3. Clustering allows Node.js to run with other languages like Python
4. Clustering allows Node.js to run in different operating systems
simultaneously

Correct Response: Option 2


Explanation: Clustering is a Node.js feature that enhances application
performance. Node.js runs in a single thread, and due to this, the full
potential of multi-core systems can't be utilized. By clustering, we can
create child processes (workers), which run on different ports and share the
server load. This allows applications to scale and enhance performance.
What is a thread pool and which library handles it
in Node.js?
1. A thread pool is a group of spawned threads that can be reused to
perform tasks, handled by the 'os' library
2. A thread pool is a group of web workers, handled by the 'worker' library
3. A thread pool is a group of spawned threads that can be reused to
perform tasks, handled by the 'worker_threads' library
4. A thread pool is a group of child processes, handled by the 'cluster'
library

Correct Response: Option 3


Explanation: A thread pool is a pool of 'worker threads' that are waiting to
be used to perform a task. In Node.js, the 'worker_threads' library is used to
handle a thread pool. The thread pool is especially useful when you have
tasks that are CPU intensive and would block the event loop if run on the
main thread.
What is WASI and why is it being introduced?
1. WASI is a new database interface, it's introduced for better database
security
2. WASI is WebAssembly System Interface, it's introduced to allow
WebAssembly to be used outside the browser
3. WASI is a new HTTP protocol, it's introduced for faster data
transmission
4. WASI is a new JavaScript framework, it's introduced to compete with
Node.js

Correct Response: Option 2


Explanation: WASI stands for WebAssembly System Interface, a system
interface for the WebAssembly platform. WASI is being introduced to
enable WebAssembly applications to run anywhere, inside or outside the
browser. It allows WebAssembly to perform tasks that usually require direct
system support, like filesystem access, in a portable and secure way.
How are worker threads different from clusters?
1. Clusters run in the same process while worker threads run in different
processes
2. Clusters are used for CPU-intensive tasks while worker threads for I/O
operations
3. Worker threads run in the same process while clusters run in different
processes
4. Worker threads are used for I/O operations while clusters for CPU-
intensive tasks

Correct Response: Option 3


Explanation: Worker threads and clusters are different in Node.js. Clusters
run in their own processes while worker threads run in the same process but
in different threads. Clusters are used for scaling the application across
multiple cores, effectively utilizing all CPUs, while worker threads are used
for CPU-intensive tasks that could block the event loop.
How to measure the duration of async operations?
1. By using the 'timer' module in Node.js
2. By checking the system clock
3. By using 'console.time' and 'console.timeEnd'
4. By calculating the difference between the start and end of an operation

Correct Response: Option 3


Explanation: The duration of async operations in Node.js can be measured
using 'console.time' and 'console.timeEnd'. By providing the same string
label to these methods, Node.js can calculate the time spent between these
two calls, even for async operations.
How to measure the performance of async
operations?
1. By using the 'performance' module in Node.js
2. By checking the system clock
3. By using 'console.time' and 'console.timeEnd'
4. By using 'PerformanceObserver' and 'performance' object in the
'perf_hooks' module

Correct Response: Option 4


Explanation: The performance of async operations in Node.js can be
measured using 'PerformanceObserver' and 'performance' object in the
'perf_hooks' module. This allows you to observe various performance
metrics like the time to first byte (TTFB) or the duration of a function call.
What are the advantages and disadvantages of
using Node.js for microservices architecture?
1. Advantage: It's faster than other languages; Disadvantage: It doesn't
support multi-threading
2. Advantage: It's non-blocking I/O model is perfect for microservices;
Disadvantage: It can be hard to maintain if the application gets large
3. Advantage: It supports multi-threading; Disadvantage: It's slower than
other languages
4. Advantage: It's easier to use than other languages; Disadvantage: It
doesn't have good support for microservices

Correct Response: Option 2


Explanation: One of the main advantages of using Node.js for a
microservices architecture is its non-blocking I/O model which allows it to
handle multiple requests concurrently. This is perfect for microservices as
they often need to handle a lot of requests and can't afford to block the main
thread. The main disadvantage is that, as applications grow, the code base
can become difficult to maintain. This can be mitigated by following good
development practices, using tools like linters, and writing comprehensive
tests.
What is the difference between using
'eventEmitter.once' and 'eventEmitter.on'
methods in Node.js?
1. 'eventEmitter.once' listens to an event only once while 'eventEmitter.on'
listens to an event indefinitely
2. 'eventEmitter.once' listens to an event indefinitely while 'eventEmitter.on'
listens to an event only once
3. 'eventEmitter.once' and 'eventEmitter.on' have the same functionality
4. 'eventEmitter.once' emits an event while 'eventEmitter.on' listens to an
event

Correct Response: Option 1


Explanation: The 'eventEmitter.on' method in Node.js is used to register
listeners that listen to an event indefinitely, while 'eventEmitter.once'
method is used to register a listener that can only respond once to an event
emission. After 'eventEmitter.once' has responded to an event, it is
unregistered and will not respond to any further emissions of the event.
How does garbage collection work in Node.js, and
how can you manually trigger it?
1. Garbage collection in Node.js is automatic and cannot be manually
triggered
2. Node.js does not have a garbage collector
3. Garbage collection in Node.js works by deleting objects that are not in
use, it can be manually triggered using global.gc() if the --expose-gc flag is
set
4. Node.js uses reference counting for garbage collection, it can be
manually triggered using process.gc()

Correct Response: Option 3


Explanation: Garbage collection in Node.js works by automatically freeing
up the memory that is no longer in use by the application, it uses a
mechanism called 'mark-and-sweep'. It can be manually triggered using
'global.gc()' if the Node.js application is started with the --expose-gc flag.
However, it's not recommended to manually trigger garbage collection in a
production application as it may halt the execution momentarily.
How can you handle unhandled promise
rejections in Node.js?
1. By using the 'unhandledRejection' event on process object
2. By using the 'uncaughtException' event on process object
3. By using 'try/catch' in all promises
4. By using a third-party library

Correct Response: Option 1


Explanation: In Node.js, unhandled promise rejections can be caught at the
process level using the 'unhandledRejection' event on process object. This
event is emitted when a promise is rejected and no error handler is attached
to the promise within a turn of the event loop. By listening on this event,
you can log the error and even exit the process if it's not possible to recover
from the error.
What is the purpose of the 'crypto' module in
Node.js, and how is it used?
1. 'crypto' module is used for creating user interfaces
2. 'crypto' module is used for performing cryptographic operations
3. 'crypto' module is used for handling HTTP requests
4. 'crypto' module is used for handling events in the browser

Correct Response: Option 2


Explanation: The 'crypto' module in Node.js is used for performing
cryptographic operations like encryption, decryption, and hashing. It
provides a way of handling data securely, which is essential for tasks like
password storage, data integrity checks, digital signatures, etc. For example,
you can use the 'createHmac' method to create a cryptographic HMAC
digest, or use the 'createCipheriv' method to encrypt data.
Explain how the 'os' module in Node.js works.
1. 'os' module is used for creating user interfaces
2. 'os' module is used for performing cryptographic operations
3. 'os' module is used for providing operating system-related utility methods
and properties
4. 'os' module is used for handling events in the browser

Correct Response: Option 3


Explanation: The 'os' module in Node.js is used to provide operating
system-related utility methods and properties. It allows developers to
interact with the underlying operating system in various ways, like getting
the OS platform, total system memory, free memory, home directory,
uptime, load averages, etc. It can be used for getting system-level
information, managing user information, or handling file paths in an OS-
agnostic way.
How can you handle file uploads in Express.js?
1. File uploads can be handled using 'fs' module
2. File uploads can be handled using 'crypto' module
3. File uploads can be handled using 'multer' middleware
4. File uploads can be handled using 'os' module

Correct Response: Option 3


Explanation: In Express.js, file uploads can be handled using 'multer'
middleware. Multer provides several options for managing uploaded files,
such as determining where to store files, what to name them, and what to do
with the file data. By configuring multer and using it as middleware in your
routes, you can easily handle single or multiple file uploads.
How can you implement server-side rendering
with Node.js?
1. By using the 'http' module and sending the HTML as a response
2. By using the 'crypto' module
3. By using a third-party library like 'React' or 'Next.js'
4. By using the 'os' module

Correct Response: Option 3


Explanation: While you can implement server-side rendering (SSR) in
Node.js using the native 'http' module, it's often more practical and efficient
to use third-party libraries like 'React' or 'Next.js'. These libraries have
built-in support for SSR, which can improve initial page load times and
SEO performance. They allow you to render your JavaScript views on the
server and then send the HTML to the client.
How can you prevent or mitigate denial-of-service
attacks in a Node.js application?
1. By limiting the rate of requests using middleware like 'express-rate-limit'
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: One way to prevent or mitigate denial-of-service attacks in a
Node.js application is by limiting the rate of requests a single client can
make. This can be achieved using middleware like 'express-rate-limit'. Rate
limiting can prevent a single malicious client from overwhelming the server
with requests, effectively denying service to other clients. Other strategies
may include using a reverse proxy, implementing CAPTCHAs, and using
robust authentication and session management.
How do you manage sessions in Express.js?
1. By using the 'express-session' middleware
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Session management in Express.js can be accomplished by
using 'express-session' middleware. 'express-session' is a Node.js module
available through the npm registry. It provides a way to persist data across
requests, such as storing user data between pages. The session data is stored
server-side, while a cookie containing a session ID is stored in the user's
browser.
Explain how Node.js's 'net' module is used to
create both servers and clients.
1. 'net' module is used to create server-side rendering
2. 'net' module is used to create user interfaces
3. 'net' module is used to provide network communication capabilities
4. 'net' module is used to handle events in the browser

Correct Response: Option 3


Explanation: The 'net' module in Node.js provides an API for creating
network servers and clients. It includes methods for creating both TCP and
IPC servers and clients. For example, 'net.createServer' can be used to
create a TCP or local server, and 'net.connect' can be used to create a client
that connects to a server. This is useful for any kind of low-level network
communication, such as creating an HTTP server or interacting with other
servers.
What is a duplex stream in Node.js, and where
might it be used?
1. A duplex stream is a type of stream that can be read from and written to,
and it might be used in file reading and writing operations
2. A duplex stream is a type of stream that can only be read from
3. A duplex stream is a type of stream that can only be written to
4. A duplex stream is a type of stream that cannot be read from or written to

Correct Response: Option 1


Explanation: A duplex stream in Node.js is a type of stream that can be both
read from and written to. This means data can be piped into and out of the
stream. Duplex streams are useful in scenarios like network
communications, where data needs to be sent and received concurrently.
Examples include TCP sockets where data can be written to send to a client
and read to receive data from a client.
What are the use cases for using Node.js with
WebSocket?
1. For building single page applications
2. For building server-side rendered applications
3. For building real-time applications like chat apps, gaming servers, live
updates in web applications, etc.
4. For building command-line applications

Correct Response: Option 3


Explanation: Node.js combined with WebSocket is primarily used for
building real-time web applications. This is due to the persistent connection
established between the client and server, allowing for instant data push and
pull. Examples of real-time applications that benefit from Node.js and
WebSocket include chat applications, multiplayer gaming servers,
collaborative editing tools, live text updates, real-time analytics, etc.
How can you run Node.js applications as different
users?
1. By using the 'sudo' command on Unix-based systems
2. By using the 'net' module
3. By using the 'os' module
4. By using the 'http' module

Correct Response: Option 1


Explanation: On Unix-based systems, you can use the 'sudo' command to
run your Node.js application as a different user. By using the '-u' or '--user'
option followed by the username, the command runs with the privileges of
that specified user. This can be useful for managing permissions and
ensuring the security of your system. However, always exercise caution
when using 'sudo' as it provides elevated privileges and can impact your
system if used incorrectly.
How can you prevent your Node.js process from
crashing when an uncaught exception occurs?
1. By listening to the 'uncaughtException' event on the process object
2. By using 'try/catch' blocks in all synchronous code
3. By using a third-party library
4. By using the 'os' module

Correct Response: Option 1


Explanation: In Node.js, uncaught exceptions can be caught at the process
level by listening to the 'uncaughtException' event on the process object.
This event is emitted when an uncaught JavaScript exception bubbles all the
way back to the event loop. By listening on this event, you can log the error
and clean up any resources before exiting. However, the application is in an
undefined state after an uncaught exception, and it's recommended to restart
the process after an 'uncaughtException' event.
How can you manage environment variables in a
Node.js application?
1. By using the global 'process.env' object or libraries like 'dotenv'
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Environment variables in a Node.js application can be
managed by using the global 'process.env' object. This object contains the
user environment and can be used to configure the behavior of the
application based on the environment it's running in. For more complex
use-cases, libraries like 'dotenv' can be used which loads environment
variables from a .env file into 'process.env'. This allows you to separate
secrets from your source code.
What strategies can be used to handle database
operations efficiently in Node.js?
1. Using connection pooling, database caching, batch operations, query
optimization, and efficient schema design
2. Using the 'crypto' module
3. Using the 'http' module
4. Using the 'os' module

Correct Response: Option 1


Explanation: To handle database operations efficiently in Node.js, there are
several strategies: using connection pooling to manage database
connections, database caching to cache frequent query results, batch
operations to execute multiple similar operations at once, query
optimization to improve the speed and efficiency of your database queries,
and efficient schema design to design your database in an optimal way.
Other strategies may include using ORM libraries like Sequelize, which
provides a high-level abstraction for managing SQL queries, or using
NoSQL databases when suitable.
What is the purpose of a Readable stream in
Node.js?
1. A Readable stream is a stream from which data can be consumed
2. A Readable stream is a stream that can only be written to
3. A Readable stream is a stream that cannot be read from or written to
4. A Readable stream is a stream that can be both read from and written to

Correct Response: Option 1


Explanation: A Readable stream in Node.js is a type of stream from which
data can be consumed. These streams effectively push data at you as soon
as it’s available instead of waiting for you to ask for the data. Examples of
readable streams include the response object from a 'http.Server' (a server-
side HTTP request), or 'fs.createReadStream' (a reading stream for
filesystem operations). They're often used when dealing with I/O between
the filesystem, network, or other data sources.
How do you implement authentication and
authorization in a Node.js application?
1. By using authentication libraries like Passport.js, implementing JSON
Web Tokens, or using OAuth
2. Using the 'crypto' module
3. Using the 'http' module
4. Using the 'os' module

Correct Response: Option 1


Explanation: Authentication and authorization in a Node.js application can
be implemented by using authentication libraries like Passport.js, which
provides various authentication strategies such as Local Strategy (username
and password), OAuth, JWT and more. JSON Web Tokens (JWT) can be
used for stateless, server-side sessions and OAuth can be used for third-
party authentication. Additionally, middleware functions can be used for
role-based authorization.
What is the purpose of using Helmet.js in
Express.js applications?
1. Helmet.js helps to secure Express.js applications by setting various
HTTP headers
2. Helmet.js helps to create user interfaces
3. Helmet.js helps to handle events in the browser
4. Helmet.js helps to create network servers and clients

Correct Response: Option 1


Explanation: Helmet.js is a middleware package for Express.js applications
that helps to secure applications by setting various HTTP headers. It
includes functions to enable or disable features like Content Security Policy,
Hide X-Powered-By, HPKP, HSTS, IE No Open, Don't Sniff Mimetype,
Frameguard, XSS Filter and more. These can help protect the application
from some well-known web vulnerabilities by properly configuring HTTP
headers.
What is the role of the 'querystring' module in
Node.js?
1. 'querystring' module provides utilities for parsing and formatting URL
query strings
2. 'querystring' module helps to create user interfaces
3. 'querystring' module helps to handle events in the browser
4. 'querystring' module helps to create network servers and clients

Correct Response: Option 1


Explanation: The 'querystring' module in Node.js provides utilities for
parsing and formatting URL query strings. It can be used to convert a URL
query string into a JavaScript object, or to serialize a JavaScript object into
a URL query string. This can be useful for tasks such as handling form
submissions or managing user input.
How can you ensure that certain functions in
Node.js only run after others have completed?
1. By using JavaScript Promises, Async/Await, or Callback functions
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: You can ensure that certain functions in Node.js only run after
others have completed by using JavaScript Promises, Async/Await, or
Callback functions. Promises and Async/Await provide a way to handle
asynchronous operations in a more synchronous manner, which can make
code easier to write and understand. Callback functions are a fundamental
part of Node.js and can also be used to control the order of operations.
How would you organize and structure a large
Express.js application?
1. By using MVC or similar patterns, separating concerns into different files
and folders, and by using modules
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Organizing and structuring a large Express.js application can
be done by using design patterns like MVC (Model-View-Controller),
separating concerns into different files and folders (e.g. routes, controllers,
services, models), and by using modules to encapsulate related
functionality. Middleware should be used effectively for error handling and
validating requests, and configuration should be separated from application
logic.
How do you implement server-sent events in
Node.js?
1. By using the EventSource API or libraries such as 'sse-stream'
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Server-sent events (SSE) can be implemented in Node.js by
using the EventSource API or libraries such as 'sse-stream'. SSE allows a
web server to push updates to a browser or client. This is accomplished by
sending messages to the client when there are updates, without the client
having to request updates regularly.
How do you handle transactions in a Node.js
application?
1. By using database specific transaction methods like
'sequelize.transaction' in Sequelize for SQL databases or 'multi' in Redis, or
by using two-phase commit for distributed transactions
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Transactions in a Node.js application can be handled by using
database specific transaction methods, such as 'sequelize.transaction' in
Sequelize for SQL databases, or 'multi' in Redis. For distributed
transactions, a two-phase commit protocol can be implemented. It's
important to note that transactions should be used judiciously as they can
lock resources and impact performance.
What are some use cases for using generators in
Node.js?
1. Generators can be used for lazy evaluation, to control asynchronous
operations, in iterative algorithms, or to produce infinite sequences
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Generators in Node.js are functions that can be exited and
later re-entered. They have a variety of use cases. They can be used for lazy
evaluation, where you generate values on demand. They can be used to
control asynchronous operations, where a generator yields a promise and
resumes when the promise is settled. They are useful in iterative algorithms
where state needs to be maintained between each call, and to produce
infinite sequences where producing the sequence all at once would be
impractical or impossible.
How can you create a memory leak in Node.js,
and how can you prevent it?
1. Memory leaks can be created by unused variables, closures, or global
variables and prevented by using proper coding practices and tools for
monitoring memory usage
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Memory leaks in Node.js can be created by a variety of
programming mistakes. These include: unused variables that are not
garbage collected; closures that reference large objects; global variables that
persist for the life of the application. To prevent memory leaks, you can use
proper coding practices like nullifying variables that are no longer in use,
careful usage of closures and global variables. Tools such as
'process.memoryUsage()' and Node.js profilers can be used to monitor
memory usage and detect leaks.
How do you handle logging in a Node.js
application?
1. By using logging libraries like Winston or Morgan, and by following
good logging practices
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Logging in a Node.js application can be handled by using
logging libraries like Winston, Morgan, or Bunyan, which provide more
robust logging features than the standard console.log. Good logging
practices should be followed, such as using different logging levels (error,
warn, info, debug), outputting machine-readable formats (like JSON), and
using log management solutions in production environments for storing,
analyzing and visualizing logs.
How do you create a real-time application in
Node.js?
1. By using technologies like WebSockets, Server-Sent Events (SSE), or
libraries like Socket.IO
2. By using the 'crypto' module
3. By using the 'http' module
4. By using the 'os' module

Correct Response: Option 1


Explanation: Creating a real-time application in Node.js typically involves
using technologies like WebSockets or Server-Sent Events (SSE), which
allow for two-way or one-way real-time communication between the client
and server. Libraries like Socket.IO can simplify the process, handling real-
time, bidirectional, and event-based communication. It works on every
platform, browser or device and is also very reliable and powerful.
What is the main purpose of using streams in
Node.js?
1. To enable synchronous data flow
2. To enable processing of data before it's fully transmitted
3. To reduce memory efficiency
4. To ensure data is transmitted in a linear fashion

Correct Response: Option 2


Explanation: In Node.js, streams are used to handle reading/writing of data
in a continuous manner. They are particularly useful when dealing with
large amounts of data, as they allow you to start processing the data as soon
as you start receiving it, without waiting for the whole data set to be fully
transmitted. This contributes to higher efficiency and better performance.
Which of the following is not a type of stream in
Node.js?
1. Readable
2. Writeable
3. Transferable
4. Duplex

Correct Response: Option 3


Explanation: There are four types of streams in Node.js: readable, writable,
duplex, and transform. A readable stream is one that can be read from, a
writable stream is one that can be written to, a duplex stream is both
readable and writable, and a transform stream is a duplex stream that can
modify or transform the data as it is written and read. Transferable is not a
type of stream in Node.js.
What is the purpose of buffer class in Node.js?
1. To handle network requests
2. To store data temporarily
3. To ensure data security
4. To schedule tasks

Correct Response: Option 2


Explanation: The Buffer class in Node.js is a global class that can be
accessed in an application without importing the buffer module. It is used to
deal with binary data. While JavaScript is great with Unicode-encoded
string data, it does not handle binary data very well. That's why Node.js
introduced the Buffer class, to provide more efficient storage of binary data.
Which of the following is not a way to handle
exceptions in Node.js?
1. Using try-catch statement
2. Using Promises
3. Using "uncaughtException" event
4. Ignoring the exceptions

Correct Response: Option 4


Explanation: Ignoring exceptions is not a recommended way to handle
exceptions in Node.js. It can lead to unpredictable behavior and bugs that
are hard to track. In Node.js, exceptions can be handled using a try-catch
statement, promises with rejection handling, or by listening to the
"uncaughtException" event which is emitted when an exception bubbles all
the way back to the event loop.
What does the 'global' object in Node.js
represent?
1. It represents the module's scope
2. It represents a local function scope
3. It represents the global namespace object
4. It represents the scope of a class

Correct Response: Option 3


Explanation: In Node.js, the 'global' object represents the global namespace
object, similar to the window object in the browser. All global variables and
functions are methods of this object. This includes built-in JavaScript
functions and variables, as well as any globally defined variables and
functions.
In Node.js, which method is used to schedule a
one-time callback after a delay of a certain
number of milliseconds?
1. process.nextTick()
2. setImmediate()
3. setTimeout()
4. setInterval()

Correct Response: Option 3


Explanation: The setTimeout() function in Node.js is used to schedule a
one-time callback after a delay of a certain number of milliseconds. It's a
part of the timers module, which contains functions to execute a function
after a given number of milliseconds.
What does the 'fs' module in Node.js provide?
1. Functionality for HTTP operations
2. Functionality for file I/O operations
3. Functionality for dealing with query strings
4. Functionality for dealing with operating system tasks

Correct Response: Option 2


Explanation: The 'fs' module in Node.js provides functionality for file I/O
operations. It allows you to work with the file system on your computer,
such as creating files, deleting files, reading files, etc.
Which method in the 'http' module is used to
create a new server?
1. http.createServer()
2. http.newServer()
3. http.createServerRequest()
4. http.requestServer()

Correct Response: Option 1


Explanation: The http.createServer() method is used to create a new server
in Node.js. This server can then listen at a specified port for HTTP requests
and provide responses.
What is the purpose of the 'path' module in
Node.js?
1. To handle network requests
2. To handle file paths
3. To handle events
4. To handle database operations

Correct Response: Option 2


Explanation: The 'path' module in Node.js is used for handling and
transforming file paths. It provides utilities for working with file and
directory paths and can be used for tasks such as finding the file extension
or joining paths together.
Which method in the 'querystring' module is used
to parse a URL query string?
1. querystring.parse()
2. querystring.stringify()
3. querystring.decode()
4. querystring.encode()

Correct Response: Option 1


Explanation: The querystring.parse() method in Node.js is used to parse a
URL query string into a collection of key and value pairs.
What does the 'events' module in Node.js provide?
1. Functionality for creating and managing custom events
2. Functionality for handling HTTP requests
3. Functionality for handling file I/O operations
4. Functionality for handling database operations

Correct Response: Option 1


Explanation: The 'events' module in Node.js provides functionality for
creating and managing custom events. It includes the EventEmitter class,
which is used to raise and handle events.
Which Node.js module would you use to spawn a
child process?
1. 'http' module
2. 'os' module
3. 'fs' module
4. 'child_process' module

Correct Response: Option 4


Explanation: The 'child_process' module in Node.js is used to spawn child
processes. It provides the ability to spawn child processes in a manner that
is similar, but more comprehensive than the popen(3) functionality in Unix.
What is the 'crypto' module in Node.js used for?
1. Handling mathematical operations
2. Providing cryptographic functionality
3. Managing child processes
4. Reading and writing data from the file system

Correct Response: Option 2


Explanation: The 'crypto' module in Node.js provides cryptographic
functionality that includes a set of wrappers for OpenSSL's hash, HMAC,
cipher, decipher, sign, and verify functions.
Which function in the 'util' module is used to
print to stdout with newline?
1. util.log()
2. util.inspect()
3. util.format()
4. util.debuglog()

Correct Response: Option 1


Explanation: The util.log() function in Node.js is used to print to stdout
with newline. This function is mostly used for debugging purposes.
How can you read environment variables in
Node.js?
1. Using 'env' module
2. Using 'process' module
3. Using 'os' module
4. Using 'path' module

Correct Response: Option 2


Explanation: Environment variables in Node.js can be read using the
'process' module. For example, process.env.NODE_ENV would read the
NODE_ENV environment variable.
Which of the following is not a method in the 'os'
module of Node.js?
1. os.freemem()
2. os.homedir()
3. os.appendfile()
4. os.uptime()

Correct Response: Option 3


Explanation: The 'os' module in Node.js provides a number of operating
system-related utility methods. However, os.appendfile() is not one of them.
This is a function provided by the 'fs' module, not the 'os' module.
Which NPM module is commonly used to connect
Node.js with a MySQL database?
1. express
2. nodemon
3. mysql
4. sequelize

Correct Response: Option 3


Explanation: The 'mysql' NPM module is commonly used to connect
Node.js with a MySQL database. This module enables JavaScript running
in Node.js to interface with MySQL databases, executing queries and
retrieving results.
What is the main method used to execute MySQL
queries in Node.js?
1. query()
2. execute()
3. mysqlQuery()
4. run()

Correct Response: Option 1


Explanation: The query() method is used to execute MySQL queries in
Node.js. This method is provided by the 'mysql' module and allows for SQL
statements to be sent to the MySQL server and processed.
How do you handle database errors in Node.js
and MySQL?
1. Using a try-catch block
2. Using the error event of the connection object
3. Ignoring the error
4. By manually checking each query

Correct Response: Option 2


Explanation: In Node.js and MySQL, you can handle database errors by
listening for the error event of the connection object. When an error occurs
during a query or anywhere else, this event will be emitted.
What method would you use to escape user input
to prevent SQL injection in Node.js and MySQL?
1. escape()
2. secure()
3. protect()
4. validate()

Correct Response: Option 1


Explanation: The escape() method can be used to escape user input in SQL
queries to prevent SQL injection. This method, provided by the 'mysql'
module, escapes query values by placing backslashes in front of special
characters and wrapping them in single quotes.
Which method would you use to end a MySQL
connection in Node.js?
1. end()
2. close()
3. terminate()
4. stop()

Correct Response: Option 1


Explanation: The end() method is used to end a MySQL connection in
Node.js. This method, provided by the 'mysql' module, terminates the
connection gracefully and ensures that all remaining queries are executed
before sending a quit packet to the MySQL server.
How can you pool MySQL connections in Node.js
for efficient reuse?
1. Using the 'pool' method of the 'mysql' module
2. By manually reusing connections
3. By using the 'pool' module
4. Node.js does not support pooling connections

Correct Response: Option 1


Explanation: In Node.js and MySQL, you can pool connections for efficient
reuse by using the createPool method of the 'mysql' module. Connection
pools help reduce the time spent establishing new connections by reusing
connections from a pool of established connections.
In the 'mysql' module, what does the
createConnection method do?
1. It establishes a new connection to the MySQL server
2. It creates a new database
3. It creates a new table in the database
4. It initiates a new query

Correct Response: Option 1


Explanation: The createConnection method in the 'mysql' module is used to
establish a new connection to the MySQL server. It returns a new
connection object, which can be used to execute queries and perform other
database operations.
How can you fetch a single row as a result of a
query in Node.js and MySQL?
1. Using the fetch() method
2. Using a LIMIT clause in the SQL query
3. Using the single() method
4. It's not possible

Correct Response: Option 2


Explanation: To fetch a single row as a result of a query in Node.js and
MySQL, you can use a LIMIT clause in your SQL query. This will limit the
number of results returned by the query, so when LIMIT 1 is used, only one
row will be returned.
How can you use placeholders in a SQL query in
Node.js and MySQL?
1. Using :placeholder syntax
2. Using ? syntax
3. Using #placeholder syntax
4. Placeholders cannot be used

Correct Response: Option 2


Explanation: In Node.js and MySQL, you can use placeholders in a SQL
query by using the ? syntax. When the query() method is called, you can
pass an array of values as the second argument, and these values will
replace the placeholders in the query. This can help prevent SQL injection.
Which of the following is not a connection option
when using the 'mysql' module?
1. host
2. user
3. password
4. query

Correct Response: Option 4


Explanation: 'query' is not a connection option when using the 'mysql'
module. The common connection options include 'host' (the hostname of
the database server), 'user' (the MySQL user to authenticate as), and
'password' (the password of that MySQL user).
Which NPM module is most commonly used to
connect Node.js with a MongoDB database?
1. express
2. mongoose
3. mongodb
4. sequelize

Correct Response: Option 2


Explanation: The 'mongoose' NPM module is most commonly used to
connect Node.js with a MongoDB database. Mongoose provides a straight-
forward, schema-based solution to model your application data with
MongoDB.
How do you define a Schema in Mongoose?
1. With the new Schema() constructor
2. With the defineSchema() method
3. With the createSchema() function
4. nan

Correct Response: Option 1


Explanation: In Mongoose, a schema is defined using the new Schema()
constructor. Schemas are used to define the structure of the data that can be
stored in a Mongoose model.
What is the purpose of the 'populate()' function in
Mongoose?
1. To fill or populate data in a specified path
2. To update a specific document in the collection
3. To delete a specific document from the collection
4. To create a new document in the collection

Correct Response: Option 1


Explanation: The 'populate()' function in Mongoose is used to automatically
replace the specified path in the document, with document(s) from other
collection(s). It is a way to create something akin to a JOIN in SQL.
What does the 'findByIdAndUpdate()' function do
in Mongoose?
1. It finds a document by ID and updates it
2. It updates the ID of a document
3. It finds a document and deletes it
4. nan

Correct Response: Option 1


Explanation: The 'findByIdAndUpdate()' function in Mongoose finds a
document by its ID and updates it. It has options that let you return the
updated document and use other helpful features.
Which method is used to save a model instance in
Mongoose?
1. save()
2. commit()
3. store()
4. persist()

Correct Response: Option 1


Explanation: The 'save()' method is used to save a model instance in
Mongoose. When you have a document that you want to save to MongoDB,
you call this method.
How do you define a model in Mongoose?
1. With the new Model() constructor
2. With the defineModel() method
3. With the mongoose.model() function
4. nan

Correct Response: Option 3


Explanation: A model in Mongoose is defined using the mongoose.model()
function. This function takes two arguments: the singular name of the
collection your model is for, and the schema you want to use in that
collection.
What is middleware in Mongoose?
1. It is software that acts as a bridge between an operating system or
database and applications
2. It is a type of software design pattern
3. It refers to functions that are executed before or after executing certain
methods
4. nan

Correct Response: Option 3


Explanation: Middleware in Mongoose refers to functions that are executed
before (pre middleware) or after (post middleware) executing certain
methods (like save, remove, etc.). These can be used to perform certain
actions, for example, to hash passwords before saving a user document.
How can you handle database errors in Node.js
and MongoDB?
1. By using a try-catch block
2. By listening for the 'error' event on the connection object
3. By using the onError() method
4. nan

Correct Response: Option 2


Explanation: In Node.js and MongoDB, you can handle database errors by
listening for the 'error' event on the connection object. This event will be
emitted when an error occurs during a database operation.
What is the purpose of the 'toObject()' function in
Mongoose?
1. To convert a Mongoose document into a plain JavaScript object
2. To convert a Mongoose document into a JSON string
3. To convert a Mongoose document into a string
4. nan

Correct Response: Option 1


Explanation: The 'toObject()' function in Mongoose is used to convert a
Mongoose document into a plain JavaScript object, ready for formatting,
manipulation, or sending over the network.
What is the 'aggregation' feature in MongoDB?
1. It is used to process data and return computed results
2. It is used to establish connections with the MongoDB server
3. It is used to authenticate with the MongoDB server
4. nan

Correct Response: Option 1


Explanation: The 'aggregation' feature in MongoDB is used to process data
records and return computed results. It groups the data from multiple
documents together and can perform a variety of operations on the grouped
data to return a single result.
What does the 'findOne()' function do in
Mongoose?
1. It finds all documents that match the query
2. It finds a single document that matches the query
3. It updates a document that matches the query
4. nan

Correct Response: Option 2


Explanation: The 'findOne()' function in Mongoose finds the first document
that matches the query. It returns a single document that satisfies the criteria
entered as an argument, or null if no match is found.
How do you validate a schema in Mongoose?
1. Using the validate() method
2. Using the check() function
3. Using the test() method
4. nan

Correct Response: Option 1


Explanation: The validate() method is used to validate a schema in
Mongoose. Schemas in Mongoose can be assigned built-in validators and
also custom validators. When a validation error occurs, Mongoose returns
an error.
How do you connect to a MongoDB database in
Mongoose?
1. Using the connect() function
2. Using the start() method
3. Using the join() function
4. nan

Correct Response: Option 1


Explanation: The connect() function is used to connect to a MongoDB
database in Mongoose. This function needs a MongoDB connection string
to establish the connection.
How can you delete a document in Mongoose?
1. Using the remove() method
2. Using the delete() method
3. Using the erase() function
4. nan

Correct Response: Option 1


Explanation: The remove() method in Mongoose is used to delete
documents that match the conditions. It operates directly on the MongoDB
database, bypassing mongoose document lifecycle hooks.
How do you add new fields to a MongoDB
document in Mongoose after it has been created?
1. By using the 'new' keyword
2. By using the set() method
3. By directly assigning the value to the document
4. nan

Correct Response: Option 3


Explanation: In Mongoose, you can add new fields to a document after it
has been created by directly assigning a value to the document. This can be
done with dot notation or square bracket notation. The save() method
should be called afterward to persist changes to the database.
What is a 'Document' in MongoDB?
1. A collection of fields
2. A collection of databases
3. A collection of schemas
4. nan

Correct Response: Option 1


Explanation: A Document in MongoDB is a record in a collection within
the database. It's similar to a row in relational databases. The document
consists of field-and-value pairs and is the basic unit of data in MongoDB.
What is a 'virtual' in Mongoose?
1. A field that is persisted to the MongoDB database
2. A field that exists for the duration of the program
3. A field that exists during the execution of a query
4. nan

Correct Response: Option 2


Explanation: A 'virtual' in Mongoose is a field that is not persisted to
MongoDB. These are fields that you can get and set, but that do not get
saved to the database. They're typically used for computed properties on
documents.
This le was downloaded from Z-Library project

Your gateway to knowledge and culture. Accessible for everyone.

z-library.se singlelogin.re go-to-zlibrary.se single-login.ru

O cial Telegram channel

Z-Access

https://wikipedia.org/wiki/Z-Library
ffi
fi

You might also like