# Node.
js Learning Guide for Interviews
## 1. Introduction to Node.js
Node.js is an open-source, cross-platform runtime environment that executes JavaScript code
outside of a browser. It is built on Chrome's V8 JavaScript engine and is widely used for server-side
and backend development.
### Key Features
- Event-driven architecture: Handles multiple requests asynchronously.
- Non-blocking I/O: Ensures high performance by avoiding thread blocking.
- Single-threaded: Manages concurrency using the event loop.
- Cross-platform: Works seamlessly on Windows, macOS, and Linux.
### Why Node.js for Backend?
- High scalability with efficient handling of concurrent requests.
- Unified JavaScript language for both frontend and backend development.
- Rich ecosystem with a vast library of NPM packages.
---
## 2. Core Concepts
### Event Loop
The event loop is the core mechanism of Node.js that processes incoming requests asynchronously.
It ensures non-blocking operations by delegating tasks to worker threads or the system kernel.
### Non-blocking I/O
Node.js performs I/O operations asynchronously, freeing the main thread to handle additional
requests.
### Single-threaded Nature
Although single-threaded, Node.js achieves concurrency through an event loop and worker threads.
---
## 3. Important Modules
### File System (fs)
Used to interact with the file system for reading, writing, and deleting files.
```javascript
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
```
### HTTP
Facilitates building web servers.
```javascript
const http = require('http');
http.createServer((req, res) => {
res.write('Hello World');
res.end();
}).listen(3000);
```
### Events
Enables event-driven programming.
```javascript
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('event', () => {
console.log('An event occurred!');
});
emitter.emit('event');
```
### Streams
Handles continuous data flow efficiently.
```javascript
const fs = require('fs');
const readStream = fs.createReadStream('example.txt');
readStream.on('data', chunk => {
console.log(chunk);
});
```
---
## 4. Express.js Basics
Express.js is a fast, minimalist web framework for Node.js.
### Setting Up a Server
```javascript
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
### Middleware
Middleware functions execute before the route handler.
```javascript
app.use((req, res, next) => {
console.log('Middleware executed');
next();
});
```
### Error Handling
```javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
```
... (The document will continue with the same structured content, limited by space)