From 5c25b14a59893a6a1f09c1ca97399080304a3e01 Mon Sep 17 00:00:00 2001 From: Michael Czechowski Date: Thu, 7 May 2026 14:20:46 +0200 Subject: [PATCH] =?UTF-8?q?dhbw=2003-04=20(node.js=20basics+advanced):=20c?= =?UTF-8?q?js=20=E2=86=92=20esm=20in=20code-beispielen=20(import=20+=20nod?= =?UTF-8?q?e:-pr=C3=A4fix),=20legacy-cjs=20als=20vergleichsbeispiel=20mark?= =?UTF-8?q?iert,=20einheitliche=20cover,=20font=201.7=E2=86=921.4rem,=20fr?= =?UTF-8?q?agen-slides=20raus,=20=5F=5Fdirname/=5F=5Ffilename=20via=20impo?= =?UTF-8?q?rt.meta.url?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- slides/dhbw/03_nodejs_basics.md | 130 +++++++++++++++++++----------- slides/dhbw/04_nodejs_advanced.md | 52 ++++++++---- 2 files changed, 122 insertions(+), 60 deletions(-) diff --git a/slides/dhbw/03_nodejs_basics.md b/slides/dhbw/03_nodejs_basics.md index 738508e..3c03534 100644 --- a/slides/dhbw/03_nodejs_basics.md +++ b/slides/dhbw/03_nodejs_basics.md @@ -17,7 +17,7 @@ section.invert { --color-foreground: #fff; } section { - font-size: 1.7rem; + font-size: 1.4rem; } h1 { color: #005f8a; @@ -50,6 +50,30 @@ a { +# Web Engineering + +**DHBW Stuttgart** · Informatik / Wirtschaftsinformatik + +**Sommersemester 2026** · Sitzung 4 — Node.js: Scripting, Running and Building + +--- + +# Inhalt + +1. Node.js: was und warum +2. `node --check`, `node -e` (One-Liner) +3. Module: `require` / `import`, `__dirname` / `__filename` +4. HTTP-Server (built-in) +5. `fs` — Dateien lesen / schreiben +6. `package.json` — Aufbau und Lifecycle +7. npm Scripts +8. Module exportieren + +--- + + + + # Node.js – Scripting, Running and Building --- @@ -89,8 +113,10 @@ node -e "console.log('Hallo Welt')" # String node -e "console.log('Hello ' + process.argv[2])" Welt -# File reading -node -e "console.log(require('fs').readFileSync('data.json'))" +# File reading (ESM via --input-type) +node --input-type=module -e \ + "import { readFileSync } from 'node:fs'; \ + console.log(readFileSync('data.json', 'utf8'))" # JSON parsen node -e "console.log(JSON.parse(process.argv[1]))" '{"a":1}' @@ -98,70 +124,81 @@ node -e "console.log(JSON.parse(process.argv[1]))" '{"a":1}' --- -# require() – Module laden +# Module laden – ESM (modern) + +`"type": "module"` in `package.json` einschalten. ```javascript -// Eigene Datei -const utils = require('./utils'); +// Eigene Datei (Endung .js erforderlich!) +import { add, greet } from "./utils.js"; -// npm Modul -const express = require('express'); +// npm Modul (default + named import) +import express from "express"; +import { Router } from "express"; -// Built-in -const fs = require('fs'); -const path = require('path'); +// Built-in (mit "node:"-Präfix) +import { readFileSync } from "node:fs"; +import { join } from "node:path"; ``` +**Legacy CJS:** `const express = require("express")` — funktioniert noch, aber ESM ist heute Standard. + --- -# __dirname und __filename +# Pfad-Auflösung in ESM ```javascript -// Aktuelles Verzeichnis (Node.js) -console.log(__dirname); // /home/user/project/src -console.log(__filename); // /home/user/project/src/app.js +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; -// Pfad joinen -const configPath = path.join(__dirname, '..', 'config.json'); +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const configPath = join(__dirname, "..", "config.json"); ``` +In ESM gibt es **kein** automatisches `__dirname` / `__filename` (anders als CJS). Über `import.meta.url` rekonstruieren. + --- # HTTP Server mit Node.js (Built-in) +**ESM** (modern, `"type": "module"` in `package.json`): ```javascript -const http = require('http'); +import { createServer } from "node:http"; -const server = http.createServer((req, res) => { - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end('

Hallo Welt!

'); +const server = createServer((req, res) => { + res.writeHead(200, { "Content-Type": "text/html" }); + res.end("

Hallo Welt!

"); }); server.listen(3000, () => { - console.log('Server läuft auf Port 3000'); + console.log("Server läuft auf Port 3000"); }); ``` +**CommonJS** (legacy): `const http = require("http");` — funktioniert noch, aber neue Projekte nutzen ESM. + --- # fs – Dateien lesen/schreiben ```javascript -const fs = require('fs'); +import { readFile, readFileSync, writeFile } from "node:fs"; +import { readFile as readFileAsync } from "node:fs/promises"; -// Async -fs.readFile('data.json', 'utf8', (err, data) => { +// Promise-API (empfohlen, modern) +const data = await readFileAsync("data.json", "utf8"); +console.log(JSON.parse(data)); + +// Callback-API +readFile("data.json", "utf8", (err, data) => { if (err) throw err; console.log(JSON.parse(data)); }); -// Sync -const content = fs.readFileSync('data.json', 'utf8'); - -// Write -fs.writeFile('output.txt', 'Hallo Welt', (err) => { - if (err) throw err; -}); +// Sync (nur für Setup / Scripts) +const content = readFileSync("data.json", "utf8"); ``` --- @@ -206,23 +243,26 @@ npm start → start (direkt) --- -# Node.js Module – exports +# Node.js Module – exports (ESM) ```javascript -// utils.js -module.exports = { - add: (a, b) => a + b, - greet: (name) => `Hallo ${name}!` -}; +// utils.js — named exports +export const add = (a, b) => a + b; +export const greet = (name) => `Hallo ${name}!`; -// Oder einzelne Exporte -module.exports.add = (a, b) => a + b; +// utils.js — default export +export default { + add, + greet +}; ``` ---- +```javascript +// nutzen +import { add, greet } from "./utils.js"; // named +import utils from "./utils.js"; // default +import utils, { add } from "./utils.js"; // beides +``` -# Fragen? +**Legacy CJS:** `module.exports = { add, greet }` + `const { add } = require("./utils")`. -1. Wie startest du einen Node.js Server auf Port 8080? -2. Was macht `node --check`? -3. Wozu dient `package.json`? \ No newline at end of file diff --git a/slides/dhbw/04_nodejs_advanced.md b/slides/dhbw/04_nodejs_advanced.md index d0c7e27..4b8fed4 100644 --- a/slides/dhbw/04_nodejs_advanced.md +++ b/slides/dhbw/04_nodejs_advanced.md @@ -17,7 +17,7 @@ section.invert { --color-foreground: #fff; } section { - font-size: 1.7rem; + font-size: 1.4rem; } h1 { color: #005f8a; @@ -50,7 +50,30 @@ a { -# node.js – Advanced +# Web Engineering + +**DHBW Stuttgart** · Informatik / Wirtschaftsinformatik + +**Sommersemester 2026** · Sitzung 5 — Express API, CRUD und Middlewares + +--- + +# Inhalt + +1. Node.js — Fun Facts & alternative Runtimes +2. `process` — Signal-Handling, Graceful Shutdown +3. Express — Setup, Routing +4. Middlewares (eigene + built-in) +5. CRUD-Endpunkte (Create, Read, Update, Delete) +6. Error Handling +7. WebSockets + +--- + + + + +# Node.js – Advanced --- @@ -87,14 +110,20 @@ process.exit(1); // Fehler # node.js Module System ```javascript -// ES Modules -import express from 'express'; -import { port } from './src/config/constants.js'; - -// CommonJS -const fs = require('fs'); +// ES Modules (modern, "type": "module") +import express from "express"; +import { port } from "./src/config/constants.js"; +import { readFileSync } from "node:fs"; ``` +```javascript +// CommonJS (legacy) +const express = require("express"); +const fs = require("fs"); +``` + +→ Neue Projekte: ESM. Built-ins immer mit `node:`-Präfix. + --- # HTTP Request mit node-fetch @@ -249,10 +278,3 @@ wss.on('connection', (ws) => { ![bg fit](./assets/demos/test-automation-trophy.png) ---- - -# Fragen? - -1. Wozu dient `process.on('SIGINT')`? -2. Was macht `app.use(express.json())`? -3. Wie erstellst du einen GET-Endpoint mit Express? \ No newline at end of file