0% found this document useful (0 votes)
18 views

Node JS

This document contains sample questions and answers about Node.js and HTTP servers. It covers topics like handling requests, reading files, HTTP methods and status codes, and building servers with Express.

Uploaded by

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

Node JS

This document contains sample questions and answers about Node.js and HTTP servers. It covers topics like handling requests, reading files, HTTP methods and status codes, and building servers with Express.

Uploaded by

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

Beginner:

Q1. How do you handle incoming HTTP requests in NodeJS?


A. Parse the URL and check if it matches a B. Use middleware functions to handle
specific path, then send a response. requests and send responses.
C. Read the request body and send a D. Use the request and response objects
response based on its contents. passed to the callback function to handle
requests and send responses.
Answer : D
Explanation:Using the "request" object, you can access information about the incoming
request, such as the URL, HTTP method, headers, and request body (if applicable). Using the
"response" object, you can send a response back to the client, specifying the status code,
headers, and body.

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');

fs.readFile('example.txt', (err, data) => {


if (err) throw err;
console.log(data.toString());
});
Explanation:The given code uses the built-in 'fs' module of NodeJS to read the contents of a
file named 'example.txt'. The 'readFile' method takes the name of the file to be read, along
with a callback function to handle the read data. If an error occurs during reading, the
callback function throws the error. Otherwise, it logs the data to the console using the
'console.log' method

Q3. Which of the following is NOT a feature of JavaScript?


A. Prototypal inheritance B. First-class functions
C. Strict typing D. Dynamic typing
Answer : C
Explanation:Strict typing is not a feature of JavaScript, as JavaScript is a dynamically typed
language that does not require variables to be declared with a specific data type.

Q4. State True or False:


To start the HTTP server in NodeJS, you should call the start method of the server object.
Answer : False
Explanation: In NodeJS, to start an HTTP server, you first need to create a server object using
the built-in "http" module, and then call the "listen" method of the server object.

Q5. What is the purpose of the HTTP request header "User-Agent"?


A. To identify the server that is responding to B. To provide information about the client
the request making the request
C. To indicate the type of content that is D. To specify the HTTP version being used
being sent in the request
Answer : B
Explanation:This header typically contains information such as the client's operating system,
browser, and version, as well as any additional software that is being used to make the
request.

Q6.Match the HTTP status code with its meaning:

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

Q9. What is the purpose of the listen() method in Node.js?


A. To start the HTTP server and make it listen B. To close the HTTP server and stop it from
for incoming requests listening for incoming requests
C. To send a response back to the client D. None of these
Answer : A
Explanation: The listen() method is used to start the HTTP server and make it listen for
incoming requests. It takes a port number and an optional callback function as its arguments.
When the server is ready to accept requests, the callback function is called.

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');

const server = http.createServer((req, res) => {


let requestBody = '';

req.on('data', chunk => {


requestBody += chunk;
});

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:

Q1. Fill in the Blank:


The ____________ header should be set to application/json when sending JSON data.
A. User-Agent B. Cache-Control
C. Content-Type D. Authorization
Answer : C
Explanation: The Content-Type header should be set to application/json when sending JSON
data.

Q2. What is a route parameter in an HTTP server?


A. A function that handles an HTTP request B. A portion of the URL that can vary
between requests
C. A header sent with an HTTP request or D. An encryption key used for securing HTTP
response traffic
Answer : B
Explanation: A route parameter is a portion of the URL that can vary between requests, such
as an ID for a specific resource. This allows the same handler function to be used for multiple
similar requests.

Q3. State True or False:


In Express, we can use regular expressions to define complex route patterns.
Answer : True
Explanation: In Express, we can use regular expressions to define more complex route
patterns, such as matching on a specific pattern of query string parameters or other request
attributes.

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.

Q5. What is the purpose of the querystring module in Node.js?


A. To send HTTP responses to the client B. To parse JSON data from the request body
C. To handle errors that occur during request D. To parse query parameters from the URL
processing
Answer : D
Explanation: The querystring module in Node.js is used to parse query parameters from the
URL. It provides methods for encoding and decoding query strings, and can be used to handle
URL-encoded data in the request body as well.

Q6. In the following Express code, what does the req.params object represent?

const express = require('express');


const app = express();

app.get('/users/:id', (req, res) => {


const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
app.listen(3000);
A. The query parameters in the URL B. The request headers
C. The dynamic route parameters in the URL D. The request body
Answer : C
Explanation: In this code, the route handler for /users/:id uses req.params.id to access the
value of the dynamic route parameter id. The req.params object contains key-value pairs of
the named route parameters in the URL.

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.

Q9. How does Express handle routing?


A. By mapping URL paths to specific request B. By using regular expressions to match URL
handlers paths
C. By dynamically generating routes based on D. By using a middleware stack to process
the request method and URL path requests before they reach the route handler
Answer : A
Explanation: Express handles routing by mapping URL paths to specific request handlers
using the app.get(), app.post(), app.put(), app.delete(), and other similar methods.

Advance:

Q1. How can you renew an SSL certificate?


A.) Generate a new private key and certificate B. Update the existing private key and
signing request (CSR), and submit the CSR to certificate with the Certificate Authority.
the Certificate Authority for signing.
C. Modify the certificate details in the D. None of the above.
website's configuration files.
Answer : A
Explanation: When an SSL certificate is due for renewal, a new private key and CSR must be
generated. The CSR is then submitted to the Certificate Authority for signing. Once the new
certificate is received, it can be installed on the server, replacing the old one. The existing
private key can be reused or replaced with a new one during this process.

Q2. Which of the following statements is true about Socket.io?


A. It can only be used for real-time B. It uses TCP as the underlying transport
communication between web clients and protocol
servers
C. It can only be used with NodeJS and not D. It supports broadcasting, namespaces,
with other server-side technologies and rooms for managing multiple clients
Answer : D
Explanation: Socket.io provides several features for managing real-time communication
between multiple clients and servers. Broadcasting enables sending messages to all
connected clients, namespaces enable organizing clients into separate communication
channels, and rooms enable managing groups of clients within a namespace.

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')
};

https.createServer(options, (req, res) => {


res.writeHead(200);
res.end('Hello World!');
}).listen(443);
Explanation: The certificate and key are read from files using the fs module and passed as
options to the https.createServer() method. A simple response is sent to the client with the
"Hello World!" message. The server listens on port 443, which is the default HTTPS port.

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.

Q9. Which of the following is true about JWT token expiration?


A. The server must manually invalidate B. Tokens are automatically invalidated when
expired tokens they expire
C. JWT tokens cannot expire D. The expiration time is included in the token
payload
Answer : D
Explanation: The token payload contains a field called "exp" that specifies the expiration
time of the token. When the token is received by the server, the server can check the
expiration time to see if the token is still valid.

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.

Q3. Which of the following is a testing framework for NodeJS applications?


A. Mocha B. Jasmine
C. Chai D. All of the above
Answer : D
Explanation: Jasmine, Mocha, and Chai are all popular testing frameworks for NodeJS
applications. They provide tools and techniques for creating and running tests, as well as
reporting on the results
Q4. State True or False:
Debugging is only necessary during development and testing, and can be turned off in
production environments.
Answer : False
Explanation: Debugging is an important part of maintaining and improving the application,
even in production environments. However, it should be used sparingly and with caution to
avoid performance and security issues.

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.

You might also like