Appearance
Kapitel 16: Erweiterte Lernswege#
🎯 Lernziele
In diesem Kapitel lernen Sie:
- ✅ Node.js Backend-Frameworks fortgeschritten (Koa, Nest.js)
- ✅ Datenbank fortgeschritten (MySQL, MongoDB)
- ✅ Full-Stack Entwicklung (Node.js + Vue/React)
- ✅ Node.js Werkzeuge entwickeln (CLI-Tools)
- ✅ Node.js Deployment & Live-Schaltung
16.1 Node.js Backend-Frameworks fortgeschritten
🌿 Koa.js (Von den Entwicklern von Express)
Besonderheiten:
- Verwendet async/await (Keine Callbacks!)
- Sehr dünn und modern
- Besser für fortgeschrittene Entwickler
Installation:
bash
npm install koaBeispiel:
javascript
const Koa = require('koa');
const app = new Koa();
const port = 3000;
// Middleware
app.use(async (ctx) => {
// ctx = context (request + response)
ctx.body = 'Hallo von Koa!';
});
app.listen(port, () => {
console.log(`🚀 Koa-Server läuft auf http://localhost:${port}`);
});🏗️ Nest.js (Fortgeschritten & Strukturiert)
Besonderheiten:
- Verwendet TypeScript
- Ähnlich wie Angular (für Backend)
- Sehr strukturiert (MVC-Architektur)
Installation:
bash
npm i -g @nestjs/cli
nest new mein-projekt
cd mein-projekt
npm run start:devBeispiel:
typescript
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();📊 Vergleich: Express vs. Koa vs. Nest.js
| Framework | Vorteile | Nachteile | Für wen? |
|---|---|---|---|
| Express | Einfach, beliebt | Veraltet (Callbacks) | Anfänger |
| Koa | Modern, async/await | Kleinere Community | Fortgeschrittene |
| Nest.js | TypeScript, strukturiert | Komplex für Anfänger | Enterprise |
16.2 Datenbank fortgeschritten
🐬 MySQL vertieft
Verbindungspool (Connection Pooling)
javascript
const mysql = require('mysql2/promise');
// Verbindungspool erstellen
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'passwort',
database: 'meine_datenbank',
waitForConnections: true,
connectionLimit: 10, // Max. 10 Verbindungen
queueLimit: 0
});
// Verbindung aus dem Pool verwenden
async function datenAbrufen() {
try {
const [rows] = await pool.execute('SELECT * FROM users');
console.log(rows);
} catch (err) {
console.error('Fehler:', err.message);
}
}
datenAbrufen();🍃 MongoDB (NoSQL Datenbank)
Besonderheiten:
- Dokumenten-orientiert (JSON-ähnlich)
- Keine SQL-Abfragen
- Besser für unstrukturierte Daten
Installation:
bash
npm install mongodbBeispiel:
javascript
const { MongoClient } = require('mongodb');
async function mongodbBeispiel() {
const client = new MongoClient('mongodb://localhost:27017');
try {
await client.connect();
const datenbank = client.db('meine_datenbank');
const sammlung = datenbank.collection('users');
// Dokument einfügen
await sammlung.insertOne({ name: 'Max', alter: 25 });
// Dokument abrufen
const benutzer = await sammlung.findOne({ name: 'Max' });
console.log(benutzer);
} finally {
await client.close();
}
}
mongodbBeispiel();📊 SQL vs. NoSQL Vergleich
| Aspekt | MySQL (SQL) | MongoDB (NoSQL) |
|---|---|---|
| Struktur | Tabellen | Dokumente (JSON) |
| Schema | Festgelegt | Flexibel |
| Skalierbarkeit | Vertikal | Horizontal |
| Beispiel | Bankwesen | Social Media |
16.3 Full-Stack Entwicklung
🔗 Node.js + Vue.js
Projektstruktur:
mein-fullstack-projekt/
├── backend/ # Node.js API
│ ├── server.js
│ └── package.json
└── frontend/ # Vue.js App
├── src/
└── package.jsonBackend (Node.js API):
javascript
// backend/server.js
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
// CORS aktivieren (für Vue.js)
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173');
next();
});
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'Max' },
{ id: 2, name: 'Anna' }
]);
});
app.listen(port, () => {
console.log(`🚀 API läuft auf http://localhost:${port}`);
});Frontend (Vue.js):
vue
<!-- frontend/src/App.vue -->
<template>
<div>
<h1>Benutzer</h1>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const users = ref([]);
onMounted(async () => {
const response = await fetch('http://localhost:3000/api/users');
users.value = await response.json();
});
</script>⚛️ Node.js + React
Frontend (React):
jsx
// frontend/src/App.jsx
import { useState, useEffect } from 'react';
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/api/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
<div>
<h1>Benutzer</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default App;16.4 Node.js Werkzeuge entwickeln
🛠️ CLI-Tool entwickeln
Ziel: Ein Kommandozeilen-Tool erstellen (wie git oder npm).
Schritt 1: Projekt initialisieren
bash
mkdir mein-cli-tool
cd mein-cli-tool
npm init -ySchritt 2: bin-Feld in package.json hinzufügen
json
{
"name": "mein-cli-tool",
"version": "1.0.0",
"bin": {
"mein-tool": "./index.js"
}
}Schritt 3: CLI-Skript erstellen (index.js)
javascript
#!/usr/bin/env node
const args = process.argv.slice(2);
const befehl = args[0];
// Shebang (#!/usr/bin/env node) ist wichtig!
// Unter Windows nicht nötig, aber unter macOS/Linux zwingend erforderlich
switch (befehl) {
case 'hallo':
console.log('Hallo von meinem CLI-Tool!');
break;
case 'rechnen':
const zahl1 = parseFloat(args[1]);
const zahl2 = parseFloat(args[2]);
console.log(`Ergebnis: ${zahl1 + zahl2}`);
break;
default:
console.log('Verfügbare Befehle: hallo, rechnen');
}Schritt 4: Global installieren (zum Testen)
bash
npm link
mein-tool hallo
# Ausgabe: Hallo von meinem CLI-Tool!
mein-tool rechnen 5 3
# Ausgabe: Ergebnis: 8🤖 Automatisierungsskripte
Beispiel: Automatisches Projekt-Erstellungsskript
javascript
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const projektName = process.argv[2] || 'mein-projekt';
// Ordnerstruktur erstellen
fs.mkdirSync(projektName);
fs.mkdirSync(path.join(projektName, 'src'));
fs.mkdirSync(path.join(projektName, 'public'));
// package.json erstellen
const packageJson = {
name: projektName,
version: '1.0.0',
main: 'src/index.js',
scripts: {
start: 'node src/index.js'
}
};
fs.writeFileSync(
path.join(projektName, 'package.json'),
JSON.stringify(packageJson, null, 2)
);
// index.js erstellen
fs.writeFileSync(
path.join(projektName, 'src', 'index.js'),
'console.log("Hallo von meinem Projekt!");'
);
console.log(`✅ Projekt "${projektName}" wurde erstellt!`);Verwendung:
bash
node skript.js mein-projekt
# Erstellt einen Ordner "mein-projekt" mit Grundstruktur16.5 Node.js Deployment & Live-Schaltung
🚀 PM2 (Prozessmanager für Node.js)
Was ist PM2?
- Verwaltet Node.js-Prozesse
- Automatischer Neustart bei Abstürzen
- Lastverteilung (Cluster-Modus)
Installation:
bash
npm install -g pm2Grundlegende Befehle:
bash
# Anwendung starten
pm2 start server.js --name "mein-api"
# Anwendung stoppen
pm2 stop mein-api
# Anwendung neustarten
pm2 restart mein-api
# Status aller Anwendungen anzeigen
pm2 status
# Logs anzeigen
pm2 logs mein-api
# Autostart beim Systemstart einrichten
pm2 startup
pm2 save🌐 Deployment auf einem Linux-Server (Beispiel)
Schritt 1: Node.js auf dem Server installieren
bash
# Unter Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
# Überprüfen
node --version
npm --versionSchritt 2: Projekt hochladen (mit Git)
bash
# Auf dem Server
git clone https://github.com/dein-benutzer/dein-projekt.git
cd dein-projekt
npm installSchritt 3: Mit PM2 starten
bash
pm2 start server.js --name "mein-api"
pm2 saveSchritt 4: Nginx als Reverse Proxy konfigurieren (Optional, aber empfohlen)
nginx
# /etc/nginx/sites-available/mein-api
server {
listen 80;
server_name deine-domain.de;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}📝 Zusammenfassung
In diesem Kapitel haben Sie gelernt:
- ✅ Fortgeschrittene Frameworks: Koa.js, Nest.js
- ✅ Datenbank fortgeschritten: MySQL Pooling, MongoDB
- ✅ Full-Stack: Node.js + Vue.js / React
- ✅ CLI-Tools und Automatisierungsskripte entwickeln
- ✅ Deployment: PM2, Server-Konfiguration
📚 Weiterführende Ressourcen
🎉 Kapitel 16 abgeschlossen! Weiter zu Kapitel 17: Lernressourcen
