0% found this document useful (0 votes)
3 views

NodeJS Key Concepts

The document outlines key concepts of Node.js, including its event-driven architecture, non-blocking I/O, and single-threaded model with worker threads. It covers modules, built-in libraries, asynchronous programming, and middleware in Express.js, along with examples for each concept. Additionally, it discusses debugging, security practices, and the cluster module for utilizing multi-core CPUs.

Uploaded by

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

NodeJS Key Concepts

The document outlines key concepts of Node.js, including its event-driven architecture, non-blocking I/O, and single-threaded model with worker threads. It covers modules, built-in libraries, asynchronous programming, and middleware in Express.js, along with examples for each concept. Additionally, it discusses debugging, security practices, and the cluster module for utilizing multi-core CPUs.

Uploaded by

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

### Node.

js Key Concepts with Examples

#### 1. Event-Driven Architecture


Node.js operates on an event-driven, asynchronous model using the EventEmitter
class.

**Example:**
```javascript
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('event', () => {
console.log('Event triggered!');
});
emitter.emit('event');
```

---

#### 2. Non-Blocking I/O


Node.js performs asynchronous operations without blocking the event loop.

**Example:**
```javascript
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
```

---

#### 3. Single-Threaded with Worker Threads


Node.js uses a single-threaded event loop for async operations, with optional
worker threads for heavy tasks.

**Example of Worker Threads:**


```javascript
const { Worker } = require('worker_threads');

const worker = new Worker(`


const { parentPort } = require('worker_threads');
parentPort.postMessage('Hello from worker!');
`, { eval: true });

worker.on('message', message => console.log(message));


```

---

#### 4. Modules
Node.js supports modular development through CommonJS (`require`) and ES Modules
(`import`).

**Example:**
```javascript
// myModule.js
module.exports = { greet: () => console.log('Hello!') };

// index.js
const { greet } = require('./myModule');
greet();
```

---

#### 5. Built-in Libraries


Node.js includes many built-in modules, such as `fs`, `http`, `path`, and `os`.

**Example with `http`:**


```javascript
const http = require('http');

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


res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});

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


```

---

#### 6. NPM (Node Package Manager)


NPM allows you to manage third-party libraries.

**Example: Installing Express:**


```bash
npm install express
```

---

#### 7. Asynchronous Programming


Node.js supports Promises and `async/await` for handling asynchronous tasks.

**Example with Async/Await:**


```javascript
const fs = require('fs').promises;

async function readFile() {


try {
const data = await fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
```

---

#### 8. Streams
Streams allow for efficient handling of continuous data flows.
**Example: Reading a File Stream:**
```javascript
const fs = require('fs');
const readStream = fs.createReadStream('file.txt');

readStream.on('data', chunk => console.log(chunk.toString()));


readStream.on('end', () => console.log('No more data.'));
```

---

#### 9. HTTP Server


Node.js is commonly used to create web servers.

**Example:**
```javascript
const http = require('http');

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


res.end('Hello, World!');
});

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


```

---

#### 10. Middleware (Express.js)


Middleware functions in Express process requests sequentially.

**Example:**
```javascript
const express = require('express');
const app = express();

app.use((req, res, next) => {


console.log('Middleware hit:', req.method, req.url);
next();
});

app.get('/', (req, res) => res.send('Hello, Express!'));


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

---

#### 11. Debugging


Use Node.js' built-in debugger or external tools like Chrome DevTools or VS Code.

**Example:**
```bash
node inspect script.js
```

---

#### 12. Security


Follow best practices like using HTTPS and handling environment variables securely.
**Example: Using dotenv for environment variables:**
```javascript
require('dotenv').config();
console.log(process.env.MY_SECRET);
```

---

#### 13. Cluster Module


Cluster allows Node.js to utilize multi-core CPUs.

**Example:**
```javascript
const cluster = require('cluster');
const os = require('os');

if (cluster.isMaster) {
const numCPUs = os.cpus().length;
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
require('./server'); // Start server in each worker
}
```

---

These key concepts and examples provide a strong foundation for understanding and
building applications with Node.js.

You might also like