
1. What is Node.js?
Answer:
Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome’s V8 engine that allows executing JavaScript code outside a browser, mainly used for building scalable server-side applications.
2. What are the key features of Node.js?
Answer:
- Event-driven and asynchronous I/O
- Single-threaded but highly scalable
- Non-blocking architecture
- Fast execution with V8 engine
- Rich ecosystem with npm (Node Package Manager)
3. What is the Event Loop in Node.js?
Answer:
The Event Loop is a mechanism that handles asynchronous callbacks. It allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel whenever possible.
4. What is the difference between process.nextTick()
and setImmediate()
?
Answer:
process.nextTick()
queues a callback to be invoked before the next event loop iteration.setImmediate()
queues a callback to be executed after the current poll phase of the event loop.
5. How does Node.js handle child threads?
Answer:
Node.js runs JavaScript on a single thread but can create child processes using the child_process
module or spawn worker threads (worker_threads
) to handle CPU-intensive tasks.
6. What is a callback in Node.js?
Answer:
A callback is a function passed as an argument to another function to be executed after a task completes, commonly used for asynchronous operations.
7. What are Promises in Node.js?
Answer:
Promises represent the eventual completion (or failure) of an asynchronous operation and provide a cleaner alternative to callbacks for handling async tasks.
8. What is middleware in Express.js?
Answer:
Middleware functions in Express.js are functions that have access to the request and response objects, and the next middleware function in the app’s request-response cycle. They are used for tasks like logging, authentication, parsing request bodies, etc.
9. How do you handle errors in Node.js?
Answer:
Errors can be handled using callbacks (by checking the first error argument), try-catch
blocks (for synchronous code), and .catch()
blocks for Promises. Express.js also has error-handling middleware.
10. What is the difference between require()
and import
?
Answer:
require()
is the Node.js CommonJS module syntax.import
is ES6 module syntax, which is supported in Node.js starting from version 12+ with"type": "module"
set inpackage.json
.
11. What is the package.json
file?
Answer:package.json
is a manifest file that contains metadata about a Node.js project, including project dependencies, scripts, version, and other configurations.
12. How do you manage dependencies in Node.js?
Answer:
Dependencies are managed using npm (Node Package Manager) or yarn. You add packages via npm install <package>
and specify versions in package.json
.
13. What is the difference between process.env
and dotenv
?
Answer:process.env
accesses environment variables available to the Node.js process. dotenv
is a package used to load environment variables from a .env
file into process.env
.
14. Explain the concept of streams in Node.js.
Answer:
Streams are objects that allow reading or writing data continuously in chunks, enabling efficient data processing for large files or network communications.
15. What are the different types of streams in Node.js?
Answer:
- Readable streams (read data)
- Writable streams (write data)
- Duplex streams (both read and write)
- Transform streams (modify data while reading/writing)
16. What is clustering in Node.js?
Answer:
Clustering allows Node.js to create child processes that share the same server port, enabling better CPU utilization and improved application performance.
17. What are some common use cases of Node.js?
Answer:
- Real-time chat applications
- APIs and backend services
- Streaming applications
- Single-page applications
- Microservices architecture
18. How do you secure a Node.js application?
Answer:
- Use HTTPS
- Validate and sanitize inputs
- Implement authentication and authorization
- Use environment variables for secrets
- Keep dependencies updated
- Prevent common attacks like XSS, CSRF
19. What is event-driven programming?
Answer:
It’s a programming paradigm where the flow is determined by events such as user actions, sensor outputs, or messages from other programs.
20. How does Node.js handle concurrency?
Answer:
Node.js uses an event-driven, non-blocking I/O model with a single-threaded event loop, allowing it to handle many concurrent operations efficiently without multiple threads.
21. What is the difference between process.nextTick()
and setTimeout()
?
Answer:
process.nextTick()
schedules a callback to be invoked before the event loop continues.setTimeout()
schedules a callback to run after a specified delay, allowing the event loop to continue.
22. What is the role of the eventEmitter
class in Node.js?
Answer:EventEmitter
is a core class in Node.js used to handle and emit events. It allows objects to listen for named events and execute callbacks when those events occur.
23. How do you handle asynchronous code in Node.js?
Answer:
Asynchronous code can be handled with callbacks, Promises, async/await
syntax, or libraries like async.js
.
24. What is the difference between synchronous and asynchronous functions in Node.js?
Answer:
- Synchronous functions block the execution until they finish.
- Asynchronous functions allow the program to continue running while waiting for operations to complete.
25. What is middleware chaining in Express.js?
Answer:
Middleware chaining is the process where multiple middleware functions execute sequentially. Each middleware can modify the request/response or pass control to the next middleware by calling next()
.
26. How do you handle file uploads in Node.js?
Answer:
File uploads are commonly handled using middleware like multer
, which parses multipart/form-data and stores files on the server.
27. What is CORS and how do you enable it in a Node.js app?
Answer:
CORS (Cross-Origin Resource Sharing) is a security feature that restricts web page scripts from making requests to different domains. It can be enabled in Node.js apps using the cors
middleware.
28. What is the difference between app.use()
and app.get()
in Express?
Answer:
app.use()
mounts middleware functions for all HTTP methods and routes.app.get()
handles HTTP GET requests for a specific route.
29. How do you debug a Node.js application?
Answer:
Using tools like the built-in node inspect
, Chrome DevTools, Visual Studio Code debugger, or adding console.log()
statements.
30. What is the significance of the package-lock.json
file?
Answer:package-lock.json
locks the exact versions of dependencies installed, ensuring consistent installs across environments.
31. What is the difference between spawn()
and fork()
in the child_process
module?
Answer:
spawn()
launches a new process with a given command. It’s used for running system commands and streams I/O.fork()
is a special case ofspawn()
used to create new Node.js processes that can communicate via IPC (Inter-Process Communication).
32. How does Node.js handle file system operations?
Answer:
Node.js uses the fs
module for file system operations, offering both synchronous and asynchronous methods to read, write, update, or delete files.
33. What is the difference between readFile()
and createReadStream()
?
Answer:
readFile()
reads the entire file into memory at once.createReadStream()
reads the file in chunks, useful for large files and streaming.
34. What is the event-driven architecture in Node.js?
Answer:
It’s a design where actions (events) trigger callbacks without blocking the main thread, allowing efficient handling of multiple concurrent connections.
35. What is the purpose of the cluster
module?
Answer:
The cluster
module allows the creation of child processes (workers) to distribute workload across CPU cores, improving performance in multi-core systems.
36. How do you handle uncaught exceptions in Node.js?
Answer:
Using the process.on('uncaughtException', callback)
event handler to catch errors that aren’t caught elsewhere, although it’s recommended to handle errors properly to avoid crashing.
37. What is the difference between blocking and non-blocking I/O?
Answer:
- Blocking I/O waits for the operation to complete before continuing.
- Non-blocking I/O allows other operations to continue while waiting for the I/O operation to finish.
38. What is the role of npm
in Node.js?
Answer:npm
is the default package manager for Node.js, used to install, manage, and share reusable code packages (modules).
39. What is a callback hell? How do you avoid it?
Answer:
Callback hell occurs when multiple nested callbacks make code hard to read and maintain. It can be avoided using Promises, async/await, or modularizing code.
40. How do you handle environment-specific configurations in Node.js?
Answer:
By using environment variables, .env
files with the dotenv
package, or configuration management tools to separate configs for development, testing, and production.
41. What is the difference between async
and defer
attributes in script tags?
Answer:
async
loads the script asynchronously and executes it as soon as it’s ready, without blocking HTML parsing.defer
also loads asynchronously but delays execution until after the HTML document has been parsed.
42. How does the cluster
module improve scalability in Node.js?
Answer:
By creating multiple worker processes that run on different CPU cores, enabling the application to handle more simultaneous connections.
43. What is an EventEmitter in Node.js?
Answer:
It’s a class that facilitates event-driven programming by allowing objects to emit named events and register listeners to handle those events.
44. How do you create a simple HTTP server in Node.js?
Answer:
Using the http
module:
jsCopyEditconst http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
});
server.listen(3000);
45. What is the difference between PUT and PATCH HTTP methods?
Answer:
- PUT replaces the entire resource.
- PATCH updates part of the resource.
46. How do you prevent callback hell in Node.js?
Answer:
By using Promises, async/await syntax, or modularizing code to keep callbacks flat and readable.
47. What is the role of package-lock.json
?
Answer:
It locks the exact versions of dependencies installed, ensuring reproducible builds across different environments.
48. How do you implement authentication in Node.js applications?
Answer:
Common methods include JWT (JSON Web Tokens), sessions with cookies, OAuth, and Passport.js middleware.
49. What is the difference between process.nextTick() and setImmediate()?
Answer:
process.nextTick()
runs callbacks before the event loop continues.setImmediate()
runs callbacks on the next iteration of the event loop.
50. How do you handle cross-origin requests in Node.js?
Answer:
By enabling CORS (Cross-Origin Resource Sharing) using the cors
middleware package, specifying allowed origins and methods.