0% found this document useful (0 votes)
21 views6 pages

Core and Advanced Node.js Concepts

The document covers core and advanced Node.js concepts, including the event loop, streams, and the role of libuv. It also discusses Express.js and middleware, detailing error handling and security practices. Additionally, it addresses performance optimization techniques and tools like PM2 for managing Node.js applications.

Uploaded by

23x51f0061
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)
21 views6 pages

Core and Advanced Node.js Concepts

The document covers core and advanced Node.js concepts, including the event loop, streams, and the role of libuv. It also discusses Express.js and middleware, detailing error handling and security practices. Additionally, it addresses performance optimization techniques and tools like PM2 for managing Node.js applications.

Uploaded by

23x51f0061
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

Core Node.

js Concepts

1.​ What is [Link], and how does it work?

[Link] is a runtime environment that allows JavaScript to run on the server side. It
uses the V8 JavaScript engine and operates on a single-threaded, event-driven
architecture, making it lightweight and efficient for I/O-heavy tasks.

2.​ What is the Event Loop in [Link]?

The Event Loop is a mechanism that allows [Link] to perform non-blocking I/O
operations. It continuously checks the call stack and processes events from the event
queue, enabling asynchronous behavior.

3.​ What is the role of libuv in [Link]?

libuv is a C library that provides the Event Loop and handles asynchronous I/O
operations like file system tasks, networking, and timers.

4.​ What is the difference between setImmediate() and [Link]()?

[Link]() executes immediately after the current operation, before the Event
Loop continues.
setImmediate() executes in the next iteration of the Event Loop.

5.​ How does [Link] handle child threads?

[Link] uses the worker_threads module to create child threads for CPU-intensive
tasks, keeping the main thread free for I/O operations.

6.​ What is the purpose of the Buffer class in [Link]?

The Buffer class is used to handle binary data directly, which is essential for working
with files, network protocols, and other I/O operations.
7.​ What are streams in [Link]?

Streams are collections of data that allow processing data in chunks instead of loading
it all into memory at once. They improve performance and efficiency.

8.​ What are the different types of streams in [Link]?

Readable (e.g., reading a file)


Writable (e.g., writing to a file)
Duplex (e.g., TCP sockets)
Transform (e.g., zlib compression)

9.​ What is the difference between require and import?

require is CommonJS syntax, used in [Link] for module loading.


import is ES6 syntax, used for static module loading in modern JavaScript.

10. What is the global object in [Link]?

The global object is similar to the window object in browsers. It contains global
variables and functions available throughout the application.
Advanced [Link] Concepts

1.​ How does clustering improve [Link] performance?

Clustering allows you to create multiple instances of your [Link] application (workers)
to leverage multi-core systems, improving performance by distributing the load across
CPUs.

2.​ What is the purpose of the cluster module in [Link]?

The cluster module enables the creation of child processes (workers) that share the
same server port, allowing [Link] to handle more requests efficiently.

3.​ How do you handle memory leaks in [Link]?

Use tools like node-inspect or Chrome DevTools to identify memory leaks. Common
fixes include clearing timers, closing database connections, and avoiding global
variables.

4.​ What is the EventEmitter class in [Link]?

The EventEmitter class is used to create and handle custom events in [Link]. It is the
foundation of the event-driven architecture.

5.​ What is the difference between spawn(), exec(), and fork() in the child_process
module?

spawn(): Launches a new process and returns a stream.


exec(): Runs a command in a shell and buffers the output.
fork(): A special case of spawn() used to create child processes for [Link] modules.

6.​ What is the purpose of the util module in [Link]?

The util module provides utility functions like promisify (to convert callback-based
functions to promises) and inherits (for inheritance).
7.​ How do you debug a [Link] application?

Use [Link], node-inspect, or debugging tools in IDEs like VS Code. For advanced
debugging, use Chrome DevTools or ndb.

8.​ What is the purpose of the fs module in [Link]?

The fs module provides APIs to interact with the file system, such as reading, writing,
and deleting files.

9.​ What is the difference between readFile and createReadStream in the fs module?

readFile: Reads the entire file into memory


createReadStream: Reads the file in chunks, making it more memory-efficient for large
files.

10. What is the purpose of the path module in [Link]?

The path module provides utilities to work with file and directory paths, such as joining
paths, resolving relative paths, and extracting file extensions.
[Link] and Middleware

1.​ What is [Link]?

[Link] is a web application framework for [Link] that simplifies building APIs and
web applications by providing routing, middleware, and other utilities.

2.​ What is middleware in [Link]?

Middleware are functions that have access to the request (req), response (res), and the
next middleware in the cycle. They are used for tasks like logging, authentication, and
error handling.

3.​ How do you handle errors in [Link]?

Use error-handling middleware with four arguments: (err, req, res, next). This
middleware catches errors and sends appropriate responses.

4.​ What is the purpose of [Link]() in [Link]?

[Link]() is used to mount middleware functions that are executed for every request to
the application.

5.​ What is the difference between [Link]() and [Link]() in [Link]?

[Link](): Handles HTTP GET requests for a specific route.


[Link](): Mounts middleware for all HTTP methods or specific routes.
Performance and Security

1.​ How do you secure a [Link] application?

Use HTTPS, validate user input, sanitize data, implement authentication (e.g., JWT),
and regularly update dependencies to patch vulnerabilities.

2.​ What is the purpose of the helmet middleware in [Link]?

Helmet helps secure Express apps by setting HTTP headers like


X-Content-Type-Options and X-Frame-Options.

3.​ What is the purpose of the cors middleware in [Link]?

The cors middleware enables Cross-Origin Resource Sharing (CORS), allowing or


restricting requests from different domains.

4.​ How do you optimize the performance of a [Link] application?

Use clustering, caching (e.g., Redis), load balancing, and efficient algorithms. Also,
minimize blocking operations and optimize database queries.

5.​ What is the purpose of the PM2 process manager?

PM2 is used to manage and monitor [Link] applications. It provides features like
auto-restart, load balancing, and logging.

Common questions

Powered by AI

Clustering in Node.js involves creating multiple instances of an application to handle concurrent connections by distributing the load across multiple CPU cores, while worker threads enable parallel execution of JavaScript code within a single Node.js process, suitable for CPU-intensive tasks. Clustering is ideal for I/O-bound applications that require handling many simultaneous requests efficiently, whereas worker threads are suited for compute-heavy processes that benefit from parallel computation, such as image processing .

Helmet middleware in Express.js enhances security by setting various HTTP headers that mitigate vulnerabilities. For instance, it can prevent cross-site scripting attacks via the Content Security Policy header, thwart clickjacking through the X-Frame-Options header, and block MIME type sniffing via the X-Content-Type-Options header. By configuring these headers, helmet significantly increases the resilience of Node.js applications to attacks and exploits .

The cluster module in Node.js enhances application performance by enabling the creation of child processes (workers) that share the same server port. This feature allows the distribution of incoming requests across multiple workers, leveraging multi-core systems to increase throughput and handle more requests concurrently. This parallelism provided by clustering improves efficient resource utilization and scalability without altering the application's core code .

To prevent and manage memory leaks in Node.js, developers can use debugging and profiling tools such as node-inspect or Chrome DevTools to identify leak sources. Common solutions include clearing unused timers, properly closing database connections, and avoiding excessive use of global variables. Using process monitoring tools like PM2 helps ensure that applications maintain optimal performance by handling restarts and managing resources effectively .

The primary difference between readFile and createReadStream in Node.js relates to memory efficiency. readFile reads an entire file into memory before processing, which can lead to high memory usage with large files. In contrast, createReadStream reads files in chunks, thereby leveraging streams to process data incrementally. This method significantly reduces memory usage and is more efficient for handling large files .

Node.js uses the worker_threads module to create child threads for CPU-intensive tasks, which helps to offload these demanding tasks from the main thread. By doing so, it keeps the main thread free to handle I/O operations, thereby maintaining responsiveness and efficiency. Worker threads allow parallel processing of tasks, which is beneficial for CPU-bound operations that would otherwise block the main event loop .

Streams in Node.js, such as Readable, Writable, Duplex, and Transform, allow data processing in chunks rather than loading entire data into memory at once. This chunk-based processing reduces memory usage and enhances performance, especially for large data sets. For instance, Readable streams are used for reading data input, Writable for output, Duplex for bidirectional data flow, and Transform for modifying or compressing data as it is written or read. This streaming capability is key in managing data efficiently and minimizing memory bottlenecks .

In Node.js, process.nextTick() executes immediately after the current operation, before the Event Loop resumes processing additional I/O tasks, whereas setImmediate() schedules a callback to execute in the next iteration of the Event Loop. This means process.nextTick() is used for urgent callbacks that need immediate execution before I/O, while setImmediate() is more appropriate for operations that can be deferred to the next event cycle .

The event-driven architecture of Node.js allows it to handle I/O operations efficiently by utilizing the Event Loop, which operates without blocking the main thread. This architecture enables Node.js to perform non-blocking I/O operations, as it continuously checks the call stack and processes events from the event queue. By doing so, Node.js can manage multiple I/O tasks concurrently, without waiting for one task to complete before starting another, thus making it lightweight and efficient .

The util module in Node.js offers a promisify function that transforms callback-based functions into promise-returning functions, facilitating modern asynchronous programming patterns. This conversion simplifies code by enabling the use of async/await syntax, making asynchronous operations easier to read and manage than traditional callback-based approaches .

You might also like