3.5 KiB
3.5 KiB
marp, theme, paginate, backgroundColor, header, footer
| marp | theme | paginate | backgroundColor | header | footer |
|---|---|---|---|---|---|
| true | gaia | true | Web Engineering – DHBW Stuttgart | Michael Czechowski – SoSe 2025 |
Node.js – Scripting, Running and Building
Node.js – Was ist das?
- JavaScript Runtime (V8 Engine)
- Server-side JavaScript
- npm Package Manager
- Ideal für: APIs, CLI Tools, Automation
node --check und node -e
# Syntax check only
node --check script.js
# One-liner
node -e "console.log('Hallo Welt')"
node -e Beispiele
# String
node -e "console.log('Hello ' + process.argv[2])" Welt
# File reading
node -e "console.log(require('fs').readFileSync('data.json'))"
# JSON parsen
node -e "console.log(JSON.parse(process.argv[1]))" '{"a":1}'
require() – Module laden
// Eigene Datei
const utils = require('./utils');
// npm Modul
const express = require('express');
// Built-in
const fs = require('fs');
const path = require('path');
__dirname und __filename
// Aktuelles Verzeichnis (Node.js)
console.log(__dirname); // /home/user/project/src
console.log(__filename); // /home/user/project/src/app.js
// Pfad joinen
const configPath = path.join(__dirname, '..', 'config.json');
HTTP Server mit Node.js (Built-in)
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hallo Welt!</h1>');
});
server.listen(3000, () => {
console.log('Server läuft auf Port 3000');
});
fs – Dateien lesen/schreiben
const fs = require('fs');
// Async
fs.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;
});
package.json – Das Herzstück
{
"name": "mein-projekt",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "node --test"
},
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"nodemon": "^3.0.0"
}
}
npm Scripts
# npm run <script>
npm run start
npm run dev
# Mit Argumenten
npm run build -- --production
# Lifecycle scripts
npm install → postinstall
npm start → start (direkt)
Node.js Module – exports
// utils.js
module.exports = {
add: (a, b) => a + b,
greet: (name) => `Hallo ${name}!`
};
// Oder einzelne Exporte
module.exports.add = (a, b) => a + b;
Fragen?
- Wie startest du einen Node.js Server auf Port 8080?
- Was macht
node --check? - Wozu dient
package.json?
