[go: up one dir, main page]

0% found this document useful (0 votes)
15 views8 pages

Node JS Question Bank Answers

The document is a Node.js question bank that provides concise answers to various questions about Node.js, including its features, modules, and best practices. It covers topics such as the Event Loop, middleware in Express.js, handling asynchronous operations, and connecting to databases. The document also includes code examples for practical understanding of concepts like creating servers and using EventEmitter.

Uploaded by

iamtahereditz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views8 pages

Node JS Question Bank Answers

The document is a Node.js question bank that provides concise answers to various questions about Node.js, including its features, modules, and best practices. It covers topics such as the Event Loop, middleware in Express.js, handling asynchronous operations, and connecting to databases. The document also includes code examples for practical understanding of concepts like creating servers and using EventEmitter.

Uploaded by

iamtahereditz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Node.

js Question Bank - Clean Answers


please refer textbook for more detailed answers

2 Marks Questions

1. What is Node.js?

Node.js is an open-source, cross-platform runtime environment that allows you to run JavaScript
code outside the browser. It uses the V8 engine and is primarily used for building fast, scalable
server-side and networking applications.

2. What is NPM?

NPM (Node Package Manager) is the default package manager for Node.js. It allows developers to
install, share, and manage dependencies (libraries, tools) needed for their Node.js projects.

3. What is the role of the Event Loop in Node.js?

The Event Loop in Node.js handles asynchronous operations. It 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.

4. Define REPL in Node.js.

REPL stands for Read-Eval-Print-Loop. It is an interactive shell that processes Node.js expressions:

• Read the user's input,

• Evaluate the input,

• Print the result,

• Loop back for more input.

5. What is the purpose of package.json?

package.json contains metadata about a Node.js project (name, version, dependencies, scripts, etc.).
It is essential for managing project dependencies and scripts.

6. What are buffers in Node.js?

Buffers are temporary memory storage primarily used to handle binary data, such as when reading
or processing files or network packets in Node.js.
7. What is the use of __dirname and __filename in Node.js?

• __dirname: gives the directory path of the currently executing file.

• __filename: gives the absolute path of the currently executing file.

8. What is the difference between process.nextTick() and setImmediate()?

• process.nextTick(): Executes the callback immediately after the current operation, before
any I/O events.

• setImmediate(): Executes the callback on the next iteration of the Event Loop, after I/O
events.

9. What is a callback function in Node.js?

A callback function is a function passed into another function as an argument, which is executed
after the parent function has completed.

10. What is middleware in Express.js?

Middleware functions in Express.js are functions that have access to the request, response, and next
middleware. They are used for tasks like authentication, logging, and error handling.

3 Marks Questions

1. Explain the difference between exports and module.exports in Node.js.

• exports is a shorthand for module.exports.

• Both are used to export functions, objects, or primitives from a module.

• However, assigning a new object to exports doesn't affect module.exports unless they
reference the same object.

2. How does Node.js handle asynchronous operations?

Node.js handles asynchronous operations using:

• Callbacks,

• Promises,

• async/await,
• The Event Loop mechanism, which ensures non-blocking execution.

3. What is the purpose of the Cluster module in Node.js?

The Cluster module allows Node.js to create child processes (workers) that share the same server
port. It enables multi-core CPU utilization, improving the performance of Node.js applications.

4. Describe the use of streams in Node.js.

Streams are objects that let you read or write data continuously in chunks instead of loading it all at
once, improving performance. Example: Reading a file line-by-line using streams.

5. What is the difference between synchronous and asynchronous functions in Node.js?

• Synchronous functions block the execution until the operation completes.

• Asynchronous functions allow the program to continue execution without waiting for the
operation to complete.

6. How do you handle exceptions in Node.js?

• Using try...catch blocks for synchronous code.

• Handling errors in asynchronous code with callbacks, Promises (.catch()), or async/await


with try...catch.

7. What is the significance of the EventEmitter class in Node.js?

The EventEmitter class provides a way to handle events and event-driven programming by allowing
objects to emit named events and listen to them via callback functions.

8. Explain the concept of middleware in Express.js.

Middleware functions in Express.js are used to modify req and res objects, execute code, and end
the request-response cycle or call the next middleware.

9. What are the differences between readFile and createReadStream in Node.js?

• readFile: Reads the entire file into memory before processing.

• createReadStream: Reads the file in small chunks (streaming) which is memory efficient.
10. How does Node.js handle child processes?

Node.js can spawn child processes using the child_process module (spawn, exec, fork methods) for
running system commands or handling parallel tasks.

4 Marks Questions

1. Explain the architecture of Node.js and how it handles concurrent requests.

Node.js has:

• Single-threaded architecture using the Event Loop.

• Heavy tasks are offloaded to the Worker Pool via libuv.

• Asynchronous I/O operations allow multiple clients to be handled simultaneously without


blocking.

2. Describe the steps to create a RESTful API using Express.js.

1. Install Express using NPM.

2. Create a server.

3. Define routes (GET, POST, PUT, DELETE).

4. Connect to database if needed.

5. Use middleware for parsing and security.

6. Start the server and listen on a port.

3. How does the Event Loop work in Node.js?

The Event Loop constantly checks the call stack and the callback queue. If the stack is empty, it takes
the first event from the queue and pushes its callback into the stack for execution.

4. What are the different types of streams in Node.js, and how are they used?

• Readable (e.g., fs.createReadStream)

• Writable (e.g., fs.createWriteStream)

• Duplex (both read and write, e.g., TCP socket)

• Transform (modifies data, e.g., compression)


5. Explain the process of handling file uploads in Node.js.

• Use packages like multer.

• Configure multer storage.

• Create a POST route to accept file uploads.

• Handle errors and responses.

6. How can you manage environment variables in a Node.js application?

• Use process.env to access environment variables.

• Use .env files with dotenv package for easier management.

7. Describe the process of connecting a Node.js application to a MongoDB database.

• Install mongoose or mongodb package.

• Import and connect using URI.

• Define schema and model.

• Perform CRUD operations.

8. What are the best practices for securing a Node.js application?

• Use HTTPS.

• Sanitize inputs to prevent SQL Injection/XSS.

• Use authentication & authorization.

• Secure environment variables.

• Set security headers with helmet.

9. How do you implement authentication in a Node.js application?

• Use JWT (JSON Web Tokens) or sessions.

• Hash passwords with bcrypt.

• Validate tokens or session IDs on protected routes.

10. What are the common performance bottlenecks in Node.js applications, and how can they be
addressed?

• Blocking synchronous code → Use asynchronous methods.


• Poor database queries → Optimize queries.

• Memory leaks → Use tools like heapdump.

• Inefficient event listeners → Limit and manage listeners.

11. What is the role of HTTP module in Node.js?

The HTTP module allows Node.js to create an HTTP server that can listen to server ports and send
responses to clients.

12. How do you create a simple server using Node.js?

const http = require('http');

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

res.write('Hello World');

res.end();

});

server.listen(3000, () => console.log('Server running on port 3000'));

13. What is CORS and how is it handled in Node.js?

CORS (Cross-Origin Resource Sharing) allows servers to specify who can access resources.
In Node.js, handle it using cors middleware:

const cors = require('cors');

app.use(cors());

14. Explain how to perform routing in Express.js.

app.get('/', (req, res) => res.send('Home Page'));

app.post('/submit', (req, res) => res.send('Form submitted'));

Routing defines how the server responds to client requests.


15. What is the purpose of using body-parser middleware in Node.js?

body-parser parses incoming request bodies in a middleware, making the data available under
req.body.

16. Write a program which uses addListener() method of EventEmitter class.

const EventEmitter = require('events');

const emitter = new EventEmitter();

emitter.addListener('greet', () => {

console.log('Hello, World!');

});

emitter.emit('greet');

17. Write a code for selecting all records from Player's table.

const mysql = require('mysql');

const connection = mysql.createConnection({ /* credentials */ });

connection.connect();

connection.query('SELECT * FROM Players', (error, results) => {

if (error) throw error;

console.log(results);

});

connection.end();
18. Write a program to use SQL SELECT query to show data from a table using Node.js and MySQL
database.

(Same as above — Q17)

19. Write a program which uses addListener() method of EventEmitter class.

(Same as Q16)

20. Write a Program to define Module Circle.js which exports the functions area() and
circumference() and display the details on console.

Circle.js

exports.area = (r) => Math.PI * r * r;

exports.circumference = (r) => 2 * Math.PI * r;

Main File

const circle = require('./Circle');

console.log("Area: " + circle.area(5));

console.log("Circumference: " + circle.circumference(5));

You might also like