4.0 KiB
4.0 KiB
marp, theme, paginate, backgroundColor, header, footer
| marp | theme | paginate | backgroundColor | header | footer |
|---|---|---|---|---|---|
| true | gaia | true | Web Engineering – DHBW Stuttgart | Michael Czechowski – SoSe 2026 |
node.js – Advanced
node.js – Fun Facts
- Entwickelt von Ryan Dahl in 2009
- Erste serverseitige Laufzeitumgebung in JavaScript (C++)
- Inspiriert von Nginx (Non-blocking I/O)
Alternativen heute:
- Deno (2020): Rust, Tokio
- Bun (2022): Zig
process – Prozess-Steuerung
process.on("SIGINT", () => {
console.log("Received SIGINT. Closing server...");
server.close(() => {
console.log("Server closed.");
process.exit(0);
});
});
// Signale
process.exit(0); // Erfolgreich
process.exit(1); // Fehler
node.js Module System
// ES Modules
import express from 'express';
import { port } from './src/config/constants.js';
// CommonJS
const fs = require('fs');
HTTP Request mit node-fetch
// Node.js 18+ hat fetch eingebaut
const res = await fetch('https://api.example.com/data');
const data = await res.json();
// Ältere Versionen: node-fetch
import fetch from 'node-fetch';
Web Server, Builder, Bundler
# Boilerplates erstellen
npm create vite@latest my-app -- --template react
npm create svelte@latest
npm create astro@latest
# nuxt
npm install nuxt
npm run dev
Express – Grundlagen
import express from 'express';
const app = express();
app.listen(port, () => {
console.log(`Server läuft auf Port ${port}`);
});
Express – Middleware
app.use(express.json());
app.use('/api', (req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.use((req, res, next) => {
console.log('Middleware 2');
next();
});
Express – CRUD Routes
app.get('/api/:key', async (req, res) => {
const context = cache.get(req.params.key);
res.json({ context });
});
app.post('/api/:key', async (req, res) => {
const payload = req.body;
res.json({ created: cache.set(req.params.key, payload) });
});
app.put('/api/:key', async (req, res) => {
const payload = req.body;
res.json({ updated: cache.update(req.params.key, payload) });
});
app.delete('/api/:key', async (req, res) => {
cache.remove(req.params.key);
res.json({ deleted: req.params.key });
});
Express – server.listen
const server = app.listen(port, () => {
console.log(`Server läuft auf Port ${port}`);
});
server.on('error', (err) => {
console.error('Server error:', err);
});
server.close(() => {
console.log('Server geschlossen');
});
WebSockets
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client verbunden');
ws.on('message', (data) => {
console.log('Empfangen:', data.toString());
ws.send('Pong');
});
});
Fragen?
- Wozu dient
process.on('SIGINT')? - Was macht
app.use(express.json())? - Wie erstellst du einen GET-Endpoint mit Express?



