nodejs_interview_flashcards

(51 cards)

1
Q

What is Node.js?

A

Node.js is a server-side JavaScript runtime environment built on Chrome’s V8 engine that allows executing JavaScript code outside of a web browser. It uses an event-driven, non-blocking I/O model, making it lightweight and efficient for building scalable network applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between Node.js and JavaScript?

A

JavaScript is a programming language, while Node.js is a runtime environment that executes JavaScript on the server-side. JavaScript runs in browsers and manipulates the DOM, whereas Node.js runs on servers and provides APIs for file system operations, networking, and other server-side tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why is Node.js single-threaded?

A

Node.js is single-threaded to simplify development and avoid complexities of multi-threaded programming like race conditions and deadlocks. It handles concurrency through its event loop and asynchronous operations, allowing it to handle many concurrent connections efficiently without creating multiple threads.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the Event Loop in Node.js?

A

The Event Loop is the mechanism that handles asynchronous callbacks in Node.js. It continuously checks the call stack and callback queue, executing callbacks when the call stack is empty. This enables Node.js to perform non-blocking I/O operations despite being single-threaded.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Explain the difference between synchronous and asynchronous programming.

A

Synchronous programming executes code sequentially, blocking execution until each operation completes. Asynchronous programming allows operations to run in the background, enabling the program to continue executing other code without waiting for the operation to complete.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is event-driven programming in Node.js?

A

Event-driven programming is a paradigm where the flow of the program is determined by events such as user actions, sensor outputs, or messages. In Node.js, events trigger callback functions, allowing the application to respond to multiple events asynchronously without blocking execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is EventEmitter in Node.js?

A

EventEmitter is a class in Node.js that provides the ability to emit named events and register listener functions to respond to those events. Any object that emits events is an instance of EventEmitter, and when an event is triggered, all attached listeners execute synchronously.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is callback hell and how can you avoid it?

A

Callback hell (pyramid of doom) occurs when multiple nested callbacks make code difficult to read and maintain. It can be avoided by using Promises, async/await, modularizing code into named functions, or using control flow libraries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are Promises in Node.js?

A

Promises are objects representing the eventual completion or failure of an asynchronous operation. They have three states: pending, fulfilled, or rejected. Promises allow chaining with .then() for success and .catch() for errors, making asynchronous code more manageable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you use async/await in Node.js?

A

Async/await is syntactic sugar over Promises that makes asynchronous code look synchronous. The ‘async’ keyword is added before a function, and ‘await’ pauses execution until the Promise resolves. Use try/catch blocks for error handling with async/await.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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

A

process.nextTick() executes callbacks in the same phase of the event loop before moving to the next phase. setImmediate() executes callbacks in the next iteration of the event loop. process.nextTick() has higher priority and executes before I/O operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between setImmediate() and setTimeout()?

A

setTimeout() schedules code execution after a minimum delay in milliseconds. setImmediate() schedules code execution immediately after the current event loop iteration completes. setImmediate() has higher priority in I/O cycles.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a Buffer in Node.js?

A

Buffer is a class that handles binary data directly. It’s similar to an array of integers but corresponds to raw memory allocation outside the V8 heap. Buffers are used when dealing with TCP streams, file system operations, and other binary data operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are streams in Node.js?

A

Streams are objects that enable reading or writing data in chunks rather than loading everything into memory. There are four types: Readable (reading data), Writable (writing data), Duplex (both reading and writing), and Transform (modify data while reading/writing).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is Express.js and how does it differ from Node.js?

A

Express.js is a minimal and flexible web application framework built on top of Node.js. While Node.js provides the runtime environment, Express.js provides features like routing, middleware support, template engines, and simplified HTTP utility methods for building web applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is middleware in Express.js?

A

Middleware functions have access to request (req), response (res), and next() objects. They execute during the request-response cycle, can modify req/res objects, end the cycle, or call the next middleware. Examples include authentication, logging, and body parsing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are the types of middleware in Express.js?

A

There are five types: Application-level middleware (app.use()), Router-level middleware (router.use()), Error-handling middleware (4 parameters), Built-in middleware (express.json(), express.static()), and Third-party middleware (body-parser, cors, helmet).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the role of next() in middleware?

A

next() is a callback function that passes control to the next middleware in the stack. If next() is not called, the request hangs and never proceeds. Calling next(error) skips to error-handling middleware.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is package.json?

A

package.json is a manifest file that contains metadata about the project including name, version, dependencies, scripts, and configuration. It’s used by npm to manage project dependencies and provides information about the application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the difference between dependencies and devDependencies?

A

dependencies contain packages required for the application to run in production. devDependencies contain packages needed only during development and testing (like testing frameworks, build tools). Production builds typically exclude devDependencies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the purpose of module.exports?

A

module.exports is used to export functions, objects, or values from a module so they can be imported and used in other files using require(). It enables code modularization and reusability across the application.

22
Q

What is the difference between module.exports and exports?

A

module.exports is the actual object that gets returned when require() is called. exports is a reference to module.exports. Assigning a new value to exports breaks the reference, so module.exports should be used for exporting new objects or functions.

23
Q

What is npm?

A

npm (Node Package Manager) is the default package manager for Node.js. It allows developers to install, share, and manage dependencies. It provides access to the world’s largest software registry with millions of reusable packages.

24
Q

Name five built-in modules in Node.js.

A

1) fs (file system operations), 2) http (creating HTTP servers), 3) path (file path utilities), 4) os (operating system information), 5) events (EventEmitter class for event handling).

25
How do you connect MongoDB to Node.js?
Use the MongoDB driver or Mongoose ODM. Create a MongoClient object, specify connection URL with database name, and use connect() method. With Mongoose, use mongoose.connect() with connection string. Handle connection errors and success events appropriately.
26
What is Mongoose in Node.js?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides schema-based modeling, validation, type casting, query building, business logic hooks, and a more elegant API for interacting with MongoDB databases.
27
What are the common HTTP methods used in REST APIs?
GET (retrieve data), POST (create new resource), PUT (update entire resource), PATCH (partial update), DELETE (remove resource), HEAD (retrieve headers only), OPTIONS (describe communication options for resource).
28
How do you handle errors in Express.js?
Create error-handling middleware with four parameters (err, req, res, next). Use try/catch blocks in async route handlers. For unhandled promise rejections, listen to process.on('unhandledRejection'). For uncaught exceptions, use process.on('uncaughtException').
29
What is CORS and how do you handle it in Node.js?
CORS (Cross-Origin Resource Sharing) is an HTTP-header mechanism allowing servers to indicate which origins can access resources. Handle it using the 'cors' middleware package in Express.js by adding app.use(cors()) or configuring specific origins, methods, and headers.
30
What is JWT and how is it used in Node.js?
JWT (JSON Web Token) is a compact, URL-safe token for securely transmitting information between parties. In Node.js, use 'jsonwebtoken' library to sign tokens on login (jwt.sign()) and verify them on protected routes (jwt.verify()) in middleware.
31
How do you implement authentication in Node.js?
Common methods include: Session-based (using express-session), Token-based (JWT), OAuth (using passport-oauth), API keys, and Basic authentication. Token-based authentication with JWT is popular for stateless REST APIs.
32
What is Passport.js?
Passport.js is authentication middleware for Node.js that supports various authentication strategies (local, OAuth, JWT). It provides modular authentication, allowing developers to choose strategies based on application requirements and simplifies authentication implementation.
33
How do you secure a Node.js application?
Use HTTPS, implement proper authentication/authorization, validate and sanitize input, use helmet middleware for security headers, implement rate limiting, keep dependencies updated, use environment variables for secrets, enable CORS properly, and implement proper error handling.
34
What is clustering in Node.js?
Clustering allows creating multiple worker processes that share the same server port, utilizing all CPU cores. The cluster module spawns workers (one per core), with a master process managing them. This improves performance for CPU-intensive operations.
35
How do you improve Node.js application performance?
Use asynchronous operations, implement caching (Redis), optimize database queries and add indexes, use clustering, enable compression (gzip), minimize dependencies, use CDN for static assets, implement pagination, profile and monitor performance, and use worker threads for CPU-intensive tasks.
36
What is the difference between fork() and spawn()?
spawn() launches a new process with a command and streams data. fork() is a special case of spawn() specifically for Node.js processes, creating a new V8 instance with an IPC channel for communication between parent and child processes.
37
How do you handle CPU-intensive tasks in Node.js?
Offload to Worker Threads for multi-threading, use child processes, implement a queue system (Bull, RabbitMQ), move to microservices, use clustering, or delegate to external services. This prevents blocking the event loop.
38
What testing frameworks are used in Node.js?
Jest (comprehensive testing with mocking and snapshots), Mocha (flexible testing framework), Chai (assertion library), Jasmine (behavior-driven testing), SuperTest (HTTP assertion for APIs), Sinon (test spies and mocks).
39
How do you debug a Node.js application?
Use built-in debugger with node --inspect, Chrome DevTools, console.log statements, debugging tools in IDEs (VS Code debugger), logging libraries (Winston, Morgan), profiling tools (clinic.js), and error tracking services (Sentry).
40
What is the purpose of the assert module?
The assert module provides assertion functions for testing. It's used to check conditions and throw errors if assertions fail. Useful for writing simple unit tests and validating expected outcomes in functions.
41
What is REPL in Node.js?
REPL (Read-Eval-Print-Loop) is an interactive shell that reads user input, evaluates it, prints the result, and loops. It's useful for testing JavaScript code quickly, debugging, and experimenting with Node.js features.
42
What is the purpose of NODE_ENV?
NODE_ENV is an environment variable indicating the environment (development, production, test). It's used to configure application behavior, enable/disable features, set logging levels, and optimize performance based on environment.
43
What is body-parser in Node.js?
body-parser is middleware that parses incoming request bodies before handlers, making data available under req.body. It supports JSON, URL-encoded, and raw formats. In Express 4.16+, it's built-in as express.json() and express.urlencoded().
44
What is the purpose of process object in Node.js?
The process object is a global providing information and control over the current Node.js process. It includes environment variables (process.env), command-line arguments (process.argv), methods to exit (process.exit()), and events for handling errors.
45
What is microservices architecture and why use Node.js?
Microservices architecture breaks applications into small, independent services communicating via APIs. Node.js fits well due to its lightweight nature, event-driven model, efficient I/O handling, npm ecosystem, and ability to handle multiple service requests efficiently.
46
What is the difference between REST and GraphQL?
REST uses multiple endpoints for different resources with fixed data structures. GraphQL uses a single endpoint where clients specify exactly what data they need, avoiding over-fetching or under-fetching. GraphQL provides stronger typing and introspection.
47
How would you implement rate limiting in Node.js?
Use express-rate-limit middleware to limit requests based on IP addresses. Configure window size, max requests, and customize responses. For distributed systems, use Redis-based rate limiting. Implement different limits for different endpoints.
48
What are WebSockets and how are they used in Node.js?
WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time bidirectional communication. In Node.js, use Socket.IO library for WebSocket implementation with fallbacks, room support, and event-based communication.
49
How do you handle memory leaks in Node.js?
Use Chrome DevTools Memory Profiler, generate heap snapshots with heapdump, monitor with tools like memwatch-next, run with --trace-gc flag, analyze event listeners, properly close database connections, and clear timers/intervals.
50
What are environment variables and how are they used?
Environment variables store configuration data outside code. In Node.js, access via process.env. Use dotenv package to load variables from .env files. Store sensitive data like API keys, database credentials, and environment-specific configurations.
51
What is the event loop starvation?
Event loop starvation occurs when heavy synchronous operations block the event loop, preventing processing of pending events. This leads to application slowdowns or freezes. Avoid by using asynchronous operations and offloading CPU-intensive tasks.