Node JS
Node JS
Q2. Write a simple NodeJS script that reads a file named "example.txt" and prints its contents
to the console.
Answer : const fs = require('fs');
A. 200 i. The server cannot or will not process the request due to an apparent client error
B. 404 ii. The request was successful and the server is returning the requested data
C. 400 iii. The requested resource could not be found on the server
D. 500 iv. The server encountered an unexpected condition that prevented it from fulfilling
the request
Answer : A - ii, B - iii, C - i, D - iv
Explanation: 200: This status code is sent by the server to indicate that the request was
successful and the server is returning the requested data.
404: This status code is sent by the server to indicate that the requested resource could not
be found on the server.
400: This status code is sent by the server to indicate that the server cannot or will not
process the request due to an apparent client error. This could be due to missing or invalid
request parameters, for example.
500: This status code is sent by the server to indicate that the server encountered an
unexpected condition that prevented it from fulfilling the request. This could be due to a
server error or a problem with the server-side code.
Q7. Which HTTP method is typically used for retrieving data from a server?
A. PUT B. POST
C. DELETE D. GET
Answer : D
Explanation:The GET method is used for retrieving data from a server, such as a web page,
an image, or an API response. The other HTTP methods are typically used for modifying or
deleting data on the server.
Q8. What is the syntax for creating a simple HTTP server in Node.js?
A. var server = B. var server = new
http.createServer(handleRequest) http.Server(handleRequest)
C. var server = createServer(handleRequest) D. None of these
Answer : A
Explanation: The http module provides a createServer() method that creates a new HTTP
server object. The handleRequest function should be defined to handle incoming requests
and send back a response. The correct syntax for creating a simple HTTP server in Node.js is
var server = http.createServer(handleRequest).
Q10. How do you read data from a request body in an HTTP server using the http module?
Answer : You can read data from a request body in an HTTP server using the data event
of the request object. Here's an example:
const http = require('http');
req.on('end', () => {
res.end(`Received request body: ${requestBody}`);
});
});
server.listen(8080, () => {
console.log('Server listening on port 8080');
});
Explanation: In this example, we create a variable called requestBody to store the request
body. We listen for the data event of the request object and append each chunk of data to the
requestBody variable. When the end event of the request object is emitted, we send the
requestBody as the response body using the end() method of the response object.
Intermediate:
Q4. Which of the following is a valid way to send data in the request body using the fetch
API?
A. fetch('/api/data', { params: { name: B. fetch('/api/data', { body: { name: 'John' } })
'John' } })
C. fetch('/api/data', { method: 'POST', D. fetch('/api/data', { method: 'POST', body:
data: { name: 'John' } } JSON.stringify({ name: 'John' }) })
Answer : D
Explanation: To send data in the request body using the fetch API, we need to set the
method option to POST or another appropriate method, and pass the data as a string using
the body option. In this case, we also need to convert the data to a JSON string using the
JSON.stringify() method.
Q6. In the following Express code, what does the req.params object represent?
Q7. How can you handle errors that occur during request processing in an Express application
that uses the body-parser middleware package?
A. By including a try-catch block in the B. By defining an error handling middleware
middleware function that handles the request function with four arguments (err, req, res,
next)
C. By using the bodyParser.error() D. By setting an onError property in the
middleware function to catch errors bodyParser options object
Answer : B
Explanation: When an error occurs during request processing in an Express application that
uses the body-parser middleware package, the error is passed to the next error handling
middleware function in the stack. To handle these errors, we can define a middleware
function with four arguments (err, req, res, next) that will be called when an error occurs.
Q8. How can you configure the log format used by the morgan middleware package in an
Express application?
A. By passing an options object to the B. By calling the morgan.format() method
morgan() function when it is called with a string representing the desired log
format
C. By setting an environment variable with D. By passing a string representing the desired
the desired log format log format as an argument to the app.use()
method
Answer : A
Explanation: The morgan() function in an Express application can be called with an options
object that specifies the log format to use. For example, we can use morgan('combined') to
use the combined log format, or we can pass an options object with a format property to
specify a custom log format.
Advance:
Q3. How can SSL be used to secure real-time communication with Socket.io?
A. By encrypting the messages using a client- B. By generating an SSL certificate and
side script configuring it in the NodeJS server
C. By using HTTPS as the underlying D. By using a third-party service to encrypt
transport protocol and decrypt the messages
Answer : B
Explanation: This can be achieved by generating an SSL certificate and configuring it in the
NodeJS server using a library such as HTTPS or a reverse proxy server such as Nginx.
Q4. Write a Node.js code snippet to create an HTTPS server using an SSL certificate and
private key.
Answer : const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('private.key'),
cert: fs.readFileSync('public.crt')
};
Q5. Which load balancing algorithm distributes requests evenly across all servers in the pool?
A. Round-robin B. IP Hash
C. Least connections D. Random
Answer : A
Explanation: The round-robin algorithm is a common load balancing algorithm that
distributes requests evenly across all servers in the pool. Each server is assigned a number,
and requests are distributed in a circular pattern.
Q6. Which caching technique stores a copy of the response at the client side?
A. Client-side caching B. Server-side caching
C. Content delivery network (CDN) caching D. Reverse proxy caching
Answer : A
Explanation: Client-side caching involves storing a copy of the response at the client side
(e.g. in the browser cache), so that subsequent requests can be served from the cache instead
of making a new request to the server. This can improve performance and reduce server load.
Q7. Which type of database can be used with NodeJS to create a RESTful API?
A. Relational database B. NoSQL database
C. Both A and B D. None of the above
Answer : C
Explanation: NodeJS can be used with both relational databases such as MySQL and NoSQL
databases such as MongoDB to create a RESTful API.
Q8. In MongoDB, which operator is used to query for documents that match multiple
conditions?
A. $or B. $and
C. $not D. $exists
Answer : B
Explanation: In MongoDB, the $and operator is used to query for documents that match
multiple conditions.
Expert:
Q1. Which of the following is NOT a common technique for implementing communication
between microservices in a NodeJS application?
A. REST API calls B. Message queues
C. RPC (Remote Procedure Call) D. Direct database access
Answer : D
Explanation: Directly accessing a database from a microservice can lead to tightly-coupled
components, which goes against the principles of a microservices architecture.
Q2. What is the difference between clustering and worker threads in NodeJS?
A. Clustering allows multiple instances of B. Clustering is used to distribute incoming
the same application to run on different requests across multiple servers, while worker
servers, while worker threads run within a threads are used to offload CPU-intensive tasks
single application instance from the main thread
C. Clustering and worker threads are two D. None of the above
names for the same concept
Answer : B
Explanation: Clustering is used to distribute incoming requests across multiple server
instances, while worker threads are used to run CPU-intensive tasks in separate threads
within a single server instance.
Q5. Which of the following is NOT a technique for handling SQL injection attacks in NodeJS
applications?
A. Hashing passwords B. Escaping user input
C. Parameterized queries D. Prepared statements
Answer : A
Explanation: Hashing passwords is a technique used for password storage, not for handling
SQL injection attacks.
Q6. Which of the following is a popular platform for hosting open-source NodeJS packages?
A. GitLab B. GitHub
C. npm registry D. Bitbucket
Answer : C
Explanation: The npm registry is a popular platform for hosting open-source NodeJS
packages. It allows developers to easily share and distribute their packages with other
developers.