Skip to content

Kapitel 11: Grundlegende Praxis

🎯 Lernziele

In diesem Kapitel lernen Sie:

  • ✅ Praxis 1: Einfaches Log-Tool erstellen (FS-Modul)
  • ✅ Praxis 2: Statischen Webserver erstellen (HTTP/Express)
  • ✅ Praxis 3: Einfache API-Schnittstelle entwickeln (Express)
  • ✅ Anwendung von FS-, HTTP-, und Express-Modulen

Praxis 1: Einfaches Log-Tool (FS-Modul Praxis)

📝 Anforderungsanalyse

Ziel: Ein Tool zur Aufzeichnung von Benutzeraktionen in einer lokalen Datei.

Kernfunktionalitäten:

  1. Log-Nachrichten in Datei schreiben
  2. Datum formatieren
  3. Verschiedene Log-Level (INFO, WARN, ERROR)

💻 Kernimplementierung

javascript
// logger.js
const fs = require('fs');
const path = require('path');

// Log-Level definieren
const LOG_LEVEL = {
  INFO: 'INFO',
  WARN: 'WARN',
  ERROR: 'ERROR'
};

// Datum formatieren
function datumFormatieren() {
  const jetzt = new Date();
  return jetzt.toISOString().replace('T', ' ').slice(0, 19);
}

// Log-Nachricht schreiben
function logNachricht(level, nachricht) {
  const zeitstempel = datumFormatieren();
  const logNachricht = `[${zeitstempel}] [${level}] ${nachricht}\n`;
  
  // In Konsole ausgeben
  console.log(logNachricht.trim());
  
  // In Datei schreiben
  const logDatei = path.join(__dirname, 'app.log');
  fs.appendFileSync(logDatei, logNachricht, 'utf8');
}

// Öffentliche API
module.exports = {
  info: (nachricht) => logNachricht(LOG_LEVEL.INFO, nachricht),
  warn: (nachricht) => logNachricht(LOG_LEVEL.WARN, nachricht),
  error: (nachricht) => logNachricht(LOG_LEVEL.ERROR, nachricht)
};

🧪 Code-Erklärung

Wichtige Punkte:

  1. fs.appendFileSync() - Hängt Daten an Datei an (synchron)
  2. path.join() - Plattformübergreifende Pfadverarbeitung
  3. Log-Level - Unterscheidung zwischen INFO, WARN, ERROR

▶️ Verwendung

javascript
// app.js
const logger = require('./logger');

logger.info('Anwendung gestartet');
logger.info('Verbindung zur Datenbank hergestellt');
logger.warn('Warnung: Langsame Antwortzeit');
logger.error('Fehler: Datenbankverbindung fehlgeschlagen');

Ausgabe in app.log:

[2024-01-15 10:30:15] [INFO] Anwendung gestartet
[2024-01-15 10:30:16] [INFO] Verbindung zur Datenbank hergestellt
[2024-01-15 10:30:17] [WARN] Warnung: Langsame Antwortzeit
[2024-01-15 10:30:18] [ERROR] Fehler: Datenbankverbindung fehlgeschlagen

Praxis 2: Statischer Webserver (HTTP/Express Praxis)

📝 Anforderungsanalyse

Ziel: Einen Webserver erstellen, der HTML/CSS/JS-Dateien lädt.


💻 Methode 1: Mit nativem http-Modul

javascript
// server-http.js
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // URL bereinigen
  const url = req.url.split('?')[0];
  
  // Basis-Verzeichnis
  let dateiPfad = path.join(__dirname, 'public', url === '/' ? 'index.html' : url);
  
  // Dateiendung → Content-Type
  const erweiterung = path.extname(dateiPfad);
  const mimeTypen = {
    '.html': 'text/html',
    '.css': 'text/css',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.ico': 'image/x-icon'
  };
  
  const contentType = mimeTypen[erweiterung] || 'text/plain';
  
  // Datei lesen
  fs.readFile(dateiPfad, (err, inhalt) => {
    if (err) {
      if (err.code === 'ENOENT') {
        // 404 - Datei nicht gefunden
        res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
        res.end('<h1>404 - Seite nicht gefunden</h1>');
      } else {
        // 500 - Serverfehler
        res.writeHead(500);
        res.end('Serverfehler');
      }
    } else {
      // 200 - Erfolg
      res.writeHead(200, { 'Content-Type': `${contentType}; charset=utf-8` });
      res.end(inhalt);
    }
  });
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`🚀 Statischer Server läuft auf http://localhost:${PORT}`);
});

💻 Methode 2: Mit Express (Empfohlen!)

javascript
// server-express.js
const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;

// Statische Dateien servieren
app.use(express.static(path.join(__dirname, 'public')));

// Fallback: 404 Seite
app.use((req, res) => {
  res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});

app.listen(PORT, () => {
  console.log(`🚀 Express-Server läuft auf http://localhost:${PORT}`);
  console.log('📂 Statische Dateien aus ./public werden serviert');
});

Vorteil: Viel weniger Code als mit nativem http!


📂 Projektstruktur

mein-webserver/
├── server-http.js   # HTTP-Version
├── server-express.js # Express-Version
└── public/          # Statische Dateien
    ├── index.html
    ├── style.css
    ├── script.js
    └── bilder/
        └── logo.png

Praxis 3: Einfache Schnittstelle entwickeln (Express Praxis)

📝 Anforderungsanalyse

Ziel: GET/POST-Schnittstellen erstellen, die JSON-Daten zurückgeben.


💻 Kernimplementierung

javascript
// api-server.js
const express = require('express');
const app = express();
const PORT = 3000;

// Middleware: JSON-Body parsen
app.use(express.json());

// "Datenbank" (Array)
let users = [
  { id: 1, name: 'Max', email: 'max@example.com' },
  { id: 2, name: 'Anna', email: 'anna@example.com' }
];

// ROUTES

// 1. Alle Nutzer abrufen (GET)
app.get('/api/users', (req, res) => {
  res.json({ success: true, data: users });
});

// 2. Einzelnen Nutzer abrufen (GET)
app.get('/api/users/:id', (req, res) => {
  const id = parseInt(req.params.id);
  const user = users.find(u => u.id === id);
  
  if (!user) {
    return res.status(404).json({ success: false, error: 'Nutzer nicht gefunden' });
  }
  
  res.json({ success: true, data: user });
});

// 3. Nutzer erstellen (POST)
app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  
  if (!name || !email) {
    return res.status(400).json({ success: false, error: 'Name und Email erforderlich' });
  }
  
  const newUser = {
    id: users.length + 1,
    name,
    email
  };
  
  users.push(newUser);
  
  res.status(201).json({ success: true, data: newUser });
});

// Server starten
app.listen(PORT, () => {
  console.log(`🚀 API-Server läuft auf http://localhost:${PORT}`);
  console.log('\nVerfügbare Endpunkte:');
  console.log('  GET    /api/users');
  console.log('  GET    /api/users/:id');
  console.log('  POST   /api/users');
});

🧪 API testen

Mit curl:

bash
# 1. Alle Nutzer abrufen
curl http://localhost:3000/api/users

# 2. Einzelnen Nutzer abrufen
curl http://localhost:3000/api/users/1

# 3. Nutzer erstellen
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Clara","email":"clara@example.com"}'

Mit Postman:

  1. Öffnen Sie Postman
  2. Wählen Sie GET oder POST
  3. Geben Sie http://localhost:3000/api/users ein
  4. Bei POST: Body → rawJSON{"name":"Test","email":"test@example.com"}
  5. Klicken Sie auf Send

📝 Zusammenfassung

In diesem Kapitel haben Sie gelernt:

  • ✅ Praxis 1: Log-Tool mit FS-Modul erstellen
  • ✅ Praxis 2: Statischen Webserver mit HTTP und Express erstellen
  • ✅ Praxis 3: Einfache API-Schnittstelle mit Express entwickeln

🎯 Nächste Schritte

Im nächsten Kapitel werden wir:

  • Fortgeschrittene Praxisprojekte durchführen
  • TodoList-Backend-API erstellen
  • Node.js mit Datenbank verbinden (MySQL)

📚 Weiterführende Ressourcen


🎉 Kapitel 11 abgeschlossen! Weiter zu Kapitel 12: Fortgeschrittene Praxis

Frei für alle Anfänger