Startseite / Artikel

Node.js-Befehlsreferenz für lokale Entwicklungsserver und Produktivserver

Eine scannbare Kommandoreferenz, die das Versionsmanagement von Node.js, Paketmanager, die Einrichtung der Umgebung, das Debuggen, PM2 sowie Linux-Deployment ohne Ausfallzeiten umfasst.

Verlag: REACTAPP.TOP13 Min. Lesezeit3017 Wörter

Quellen: Node.js Cheatsheet — Essential Commands for Developers and Vibe Coders in 2026

nodejs

KI-gestütztes Programmieren hat die Art und Weise, wie Projekte erstellt werden, verändert. Sie beschreiben das gewünschte Ergebnis, ein KI-Assistent generiert den Code – und schon nach wenigen Minuten läuft etwas. Doch es gibt Situationen, mit denen kein Assistent allein umgehen kann – zum Beispiel wenn Sie auf ein Terminalfenster starren und den genauen Befehl wissen müssen, den Sie eingeben sollen.

Möglicherweise bricht eine Bereitstellung auf dem Remote-Server zusammen. Vielleicht fehlschlägt eine Installation mitten im Verlauf. Oder Umgebungsvariablen weigern sich zu laden, oder ein Prozess stirbt, ohne einen nützlichen Stack-Trace zu hinterlassen. In solchen Fällen möchten Sie nicht stundenlang in Dokumentationen wühlen – Sie wollen eine schnelle Suchmöglichkeit, die Sie in Sekunden durchscannen können.

Deshalb gibt es dieses Handbuch: einen kompakten Leitfaden zu Node.js-Befehlen für zwei Kontexte – die Arbeit am lokalen Rechner sowie das Verwalten eines Produktivservers. Jeder Befehl wird mit einer kurzen Anmerkung dazu versehen, wann er das richtige Werkzeug ist.

Node.js ausführen

Begonnen wird mit den Grundlagen, die man ohne weiteres Zögern kennen sollte:

# Run a JavaScript file
node app.js

# Run with an environment variable inline
NODE_ENV=production node app.js

# Open the REPL (Read-Eval-Print Loop) - interactive Node.js shell
node

# Evaluate JavaScript directly from the terminal
node -e "console.log(process.version)"

# Check the active Node.js version
node -v
node --version


# Check the active npm version
npm -v

Nützliche CLI-Flags

# Watch mode — auto-restart when files change (Node.js 18+, no nodemon needed)
node --watch app.js

# Enable ES Modules
node --input-type=module app.js

# Increase memory limit for heavy applications
node --max-old-space-size=4096 app.js

# Show longer stack traces
node --stack-trace-limit=50 app.js

# Inspect mode for debugging with Chrome DevTools
node --inspect app.js
node --inspect-brk app.js  # Pause at first line until debugger connects

Node.js-Versionen verwalten – NVM

Für alle, die mit mehreren Projekten arbeiten, bei denen jeweils eine andere Node.js-Version erforderlich ist, wird nvm (Node Version Manager) zu einer Notwendigkeit und nicht nur zu einem praktischen Hilfsmittel.

# Install a specific Node.js version
nvm install 22
nvm install 20.11.0     # Exact version
nvm install --lts       # Latest LTS

# Switch versions
nvm use 22
nvm use --lts

# Set a default version
nvm alias default 22

# List all installed versions
nvm ls

# List available remote versions
nvm ls-remote --lts

# Use the version specified in .nvmrc
nvm use

# Create .nvmrc - lock the Node.js version for this project
echo "22" > .nvmrc

Paketmanager – npm, yarn und pnpm

Die Wahl eines Paketmanagers ist mehr als nur eine stilistische Präferenz – jede Option bringt tatsächliche Kompromisse mit sich.

Bis 2026 ist pnpm zur sinnvollen Standardwahl für die meisten Teams geworden. Es installiert sich schnell, nutzt den Festplattenspeicher effizient, vermeidet das Problem falscher Abhängigkeiten und bietet die leistungsstärksten Werkzeuge für Monorepos. Auch der Support für solche Tools hat aufgeholt – Frameworks wie Next.js, Nuxt und SvelteKit laufen alle reibungslos unter pnpm.

Trotzdem hängt es von Ihrer Situation ab, welches Tool am besten passt:

  • npm – wird standardmäßig mit Node.js mitgeliefert, funktioniert überall und ist eine zuverlässige Wahl für Einzelprojekte sowie Open-Source-Pakete
  • yarn – zeichnet sich in großen, unternehmensweiten Monorepos aus, insbesondere in Kombination mit Plug’n’Play (PnP)
  • pnpm – die schnellste und energieeffizienteste Option sowie die bevorzugte Wahl für Produktionsumgebungen und Monorepos im Jahr 2026

Kernbefehle – Alle drei Paketmanager nebeneinander

# Install all dependencies from package.json
npm install
yarn install
pnpm install

# Add a new package
npm install express
yarn add express
pnpm add express

# Add as a devDependency
npm install -D typescript
yarn add -D typescript
pnpm add -D typescript

# Remove a package
npm uninstall express
yarn remove express
pnpm remove express

# Update packages
npm update
yarn upgrade
pnpm update

# Update to latest (beyond semver range in package.json)
npm install express@latest
yarn add express@latest
pnpm add express@latest

# Install without modifying the lockfile - required in CI/CD
npm ci
yarn install --frozen-lockfile
pnpm install --frozen-lockfile

# Run a script from package.json
npm run build
yarn build
pnpm build

# Run a package executable without installing globally
npx create-next-app
yarn dlx create-next-app
pnpm dlx create-next-app

package.json – Die wichtigsten Teile

{
  "name": "my-app",
  "version": "1.0.0",
  "engines": {
    "node": ">=20.0.0",
    "npm": ">=10.0.0"
  },
  "scripts": {
    "dev": "node --watch src/index.js",
    "start": "node src/index.js",
    "build": "tsc -p tsconfig.json",
    "test": "node --test",
    "lint": "eslint src/",
    "format": "prettier --write src/"
  },
  "dependencies": {},
  "devDependencies": {},
  "type": "module"
}

Auditing und Sicherheit

# Check for vulnerabilities in dependencies
npm audit
yarn audit
pnpm audit

# Auto-fix vulnerabilities where possible
npm audit fix
yarn audit --fix
pnpm audit --fix

# List all installed packages (including nested)
npm list
npm list --depth=0    # Top-level only

# Check for outdated packages
npm outdated
yarn outdated
pnpm outdated

Umgebungsvariablen

Umgebungsvariablen ermöglichen es Ihnen, Konfigurationen zwischen Entwicklung und Produktion getrennt zu halten. Vermeiden Sie es, sensible Daten wie API-Schlüssel oder Datenbank-URLs direkt in Ihren Quellcode einzubetten.

# Create a .env file
cat > .env << EOF
NODE_ENV=development
PORT=3000
DATABASE_URL=postgresql://localhost:5432/mydb
JWT_SECRET=your-secret-key
EOF

# Make sure .env never enters version control
echo ".env"            >> .gitignore
echo ".env.local"      >> .gitignore
echo ".env.production" >> .gitignore

# Create .env.example as a template for your team
cp .env .env.example

# Then remove the sensitive values from .env.example

In Ihrem Node.js-Code:

// Node.js 20.6+ — load .env without any extra package
// Run with: node --env-file=.env app.js

// Or use dotenv for more flexibility
import 'dotenv/config';
const port    = process.env.PORT         || 3000;
const dbUrl   = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV     || 'development';

// Validate required env vars at startup - fail fast
const required = ['DATABASE_URL', 'JWT_SECRET'];
for (const key of required) {
    if (!process.env[key]) {
        console.error(`Missing required environment variable: ${key}`);
        process.exit(1);
    }
}

Modulsystem – CommonJS gegenüber ES Modules

Node.js unterstützt weiterhin zwei Modulformate, doch neue Projekte sollten standardmäßig ES Modules verwenden, da es sich um den modernen Standard handelt, der auch von Browsern genutzt wird.

// CommonJS (CJS) — the legacy format, .js or .cjs files
const fs      = require('fs');
const path    = require('path');
const express = require('express');

module.exports = { myFunction };
module.exports.default = MyClass;

// ES Modules (ESM) - the modern format, .mjs or .js with "type":"module"
import fs      from 'fs';
import path    from 'path';
import express from 'express';
import { readFile, writeFile } from 'fs/promises';
export function myFunction() {}
export default class MyClass {}

// Dynamic import - for lazy loading
const module = await import('./heavy-module.js');

Dateisystem – Die am häufigsten verwendeten Operationen

import { readFile, writeFile, appendFile,
         mkdir, rm, stat, readdir,
         copyFile, rename } from 'fs/promises';
import { existsSync }       from 'fs';
import path                 from 'path';

// Read a file
const content = await readFile('data.txt', 'utf-8');
const json    = JSON.parse(await readFile('config.json', 'utf-8'));

// Write a file
await writeFile('output.txt', 'Hello World', 'utf-8');
await writeFile('data.json', JSON.stringify(data, null, 2));

// Append to an existing file
await appendFile('log.txt', `${new Date().toISOString()} - event\n`);

// Create a directory (including missing parents)
await mkdir('logs/2026/06', { recursive: true });

// Delete a file or directory
await rm('temp-file.txt');
await rm('dist/', { recursive: true, force: true });

// Check if a file or directory exists
if (existsSync('config.json')) {
    // file exists
}

// Get file metadata
const info = await stat('app.js');
console.log(info.size);           // size in bytes
console.log(info.isDirectory());
console.log(info.mtime);          // last modified time

// Read directory contents
const files   = await readdir('./src');
const jsFiles = files.filter(f => f.endsWith('.js'));

// Path helpers - always use path.join, never string concatenation
const filePath = path.join(__dirname, 'public', 'index.html');
const ext      = path.extname('script.js');       // '.js'
const base     = path.basename('/src/app.js');    // 'app.js'
const dir      = path.dirname('/src/app.js');     // '/src'

HTTP-Server – Integriert, kein Framework erforderlich

import { createServer }     from 'http';
import { createReadStream } from 'fs';

const server = createServer(async (req, res) => {
    const url    = new URL(req.url, `http://${req.headers.host}`);
    const method = req.method;

    // Simple routing
    if (url.pathname === '/' && method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<h1>Hello World</h1>');
        return;
    }

    if (url.pathname === '/api/health' && method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ status: 'ok', timestamp: new Date() }));
        return;
    }

    // Read body from a POST request
    if (method === 'POST') {
        let body = '';
        for await (const chunk of req) {
            body += chunk;
        }
        const data = JSON.parse(body);
        // process data...
    }

    // 404
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Not Found' }));
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
});

Prozessverwaltung

// Graceful shutdown — close connections before the process exits
process.on('SIGTERM', async () => {
    console.log('SIGTERM received, shutting down...');
    await db.disconnect();
    server.close(() => {
        console.log('Server closed');
        process.exit(0);
    });
});

process.on('SIGINT', async () => {
    // Ctrl+C in terminal
    await cleanup();
    process.exit(0);
});

// Catch unhandled errors
process.on('uncaughtException', (err) => {
    console.error('Uncaught Exception:', err);
    process.exit(1); // Must exit - process state is now unreliable
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection:', reason);
    process.exit(1);
});

// Process information
console.log(process.pid);           // Process ID
console.log(process.env.NODE_ENV);  // Environment
console.log(process.argv);          // CLI arguments
console.log(process.cwd());         // Current working directory
console.log(process.memoryUsage()); // Memory usage

Debugging

# Inspect mode — open chrome://inspect in your browser
node --inspect app.js

# Pause at the first line until the debugger connects
node --inspect-brk app.js

# Enable verbose logging for specific modules
NODE_DEBUG=http,net node app.js

# CPU profiling
node --prof app.js
node --prof-process isolate-*.log > processed.txt

# Memory leak detection
node --expose-gc --inspect app.js

In Ihrem Code:

// util.debuglog — only outputs when the DEBUG env var is set
import { debuglog } from 'util';
const debug = debuglog('myapp');

debug('This only appears when: NODE_DEBUG=myapp node app.js');

// Simple timing
console.time('database-query');
await db.query('SELECT * FROM users');
console.timeEnd('database-query');

// Output: database-query: 23.456ms

PM2 – Prozessmanager für die Produktion

PM2 ist das bevorzugte Tool zum Ausführen von Node.js in der Produktion. Es startet Ihre Anwendung automatisch nach Abstürzen oder Server-Neustarts neu und kann nahezu ohne zusätzliche Einstellungen über mehrere CPU-Kerne skaliert werden.

# Install PM2 globally
npm install -g pm2

# Start an application
pm2 start app.js
pm2 start app.js --name "my-api"

# Start in cluster mode - uses all available CPU cores
pm2 start app.js -i max   # Automatically matches CPU core count
pm2 start app.js -i 4     # Exactly 4 instances

# View status of all applications
pm2 list
pm2 status

# Real-time monitoring (CPU, memory, logs)
pm2 monit

# View logs
pm2 logs
pm2 logs my-api
pm2 logs --lines 100

# Restart, reload, stop, delete
pm2 restart my-api
pm2 reload my-api    # Zero-downtime reload (cluster mode only)
pm2 stop my-api
pm2 delete my-api

# Auto-restart on server reboot
pm2 startup          # Generates the systemd command - follow the output
pm2 save             # Saves the current process list

# Configuration file
// ecosystem.config.js
export default {
    apps: [{
        name:               'my-api',
        script:             'src/index.js',
        instances:          'max',
        exec_mode:          'cluster',
        watch:              false,
        max_memory_restart: '500M',
        env: {
            NODE_ENV: 'development',
            PORT:     3000,
        },
        env_production: {
            NODE_ENV: 'production',
            PORT:     8080,
        },
        error_file:      'logs/err.log',
        out_file:        'logs/out.log',
        log_date_format: 'YYYY-MM-DD HH:mm:ss',
    }]
};
# Start from the config file
pm2 start ecosystem.config.js
pm2 start ecosystem.config.js --env production

Deployment auf einem Linux-Server

Hier ist die Abfolge, der Sie folgen sollten, wenn Sie Node.js zum ersten Mal auf einem VPS oder einer Linux-Maschine einrichten.

# 1. Update the system
sudo apt update && sudo apt upgrade -y

# 2. Install Node.js via NodeSource (latest LTS)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs

# Or install via nvm for easier version management
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install --lts
nvm use --lts

# 3. Verify the installation
node -v
npm -v

# 4. Install PM2 globally
npm install -g pm2

# 5. Clone and set up the project
git clone https://github.com/username/my-app.git
cd my-app

# 6. Install production dependencies only
npm ci --omit=dev

# or with pnpm
pnpm install --prod --frozen-lockfile

# 7. Create the production .env
nano .env

# 8. Start with PM2
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup   # Follow the printed instructions

Aktualisierung einer Bereitstellung ohne Ausfallzeiten

# Pull the latest code
git pull origin main

# Install any new dependencies
npm ci --omit=dev

# Build if needed
npm run build

# Zero-downtime reload (cluster mode only)
pm2 reload my-api

# Or a standard restart
pm2 restart my-api

Linux-Befehle, die Sie bei der Wartung von Node.js tatsächlich verwenden

# Check what's running on a specific port
lsof -i :3000
sudo netstat -tlnp | grep :3000
sudo ss -tlnp | grep :3000

# Kill whatever is on a port
kill $(lsof -t -i:3000)

# Or forcefully
kill -9 $(lsof -t -i:3000)

# Real-time resource monitoring
htop                   # Interactive (install with: apt install htop)
top                    # Built-in alternative

# Disk usage
df -h                  # Per partition
du -sh node_modules/   # Size of a specific directory
du -sh *               # Size of everything in the current directory

# Follow logs in real time
journalctl -u pm2-root -f   # PM2 logs via systemd
tail -f /var/log/syslog     # System log
tail -f logs/err.log        # Your application error log

# Memory overview
free -h

# Active network connections
ss -s

# Find all running Node.js processes
ps aux | grep node

# Find files by name or age
find . -name "*.log" -mtime +7   # .log files older than 7 days
find . -name "*.env"             # Any .env files

# Clean up old logs
find ./logs -name "*.log" -mtime +30 -delete

# Archive a folder for backup
tar -czf backup-$(date +%Y%m%d).tar.gz dist/ .env

# Transfer files to/from a server
scp -r ./dist user@server:/var/www/my-app/
rsync -avz ./dist/ user@server:/var/www/my-app/dist/

.npmrc und .nvmrc – Zwei kleine, aber wichtige Dateien

Auf den ersten Blick mögen diese beiden Konfigurationsdateien unbedeutend erscheinen, doch sie sind von großer Bedeutung, wenn Sie mit einem Team arbeiten.

# .nvmrc — pin the Node.js version for this project
# Place at the project root
echo "22" > .nvmrc

# Everyone on the team just runs:
nvm use
# NVM automatically reads the version from .nvmrc
# .npmrc — npm/pnpm configuration for this project
# Place at the project root

# Save exact versions (no ^ or ~ prefix)
save-exact=true

# Set registry (if using a private registry)
registry=https://registry.npmjs.org/

# For pnpm - allow hoisting if a package requires it
# shamefully-hoist=true
# For pnpm - set the node linker
# node-linker=hoisted

Testing – Der eingebaute Testlaufmechanismus von Node.js

Seit Node.js 20 ist ein Testlaufmechanismus bereits im Betriebssystem enthalten. Für einfache Testfälle können Sie die Installation von Jest oder Mocha völlig überspringen.

// test/app.test.js
import { test, describe, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';

describe('Calculator', () => {
    test('addition works correctly', () => {
        assert.equal(1 + 1, 2);
    });

    test('throws on division by zero', () => {
        assert.throws(
            () => divide(10, 0),
            { message: 'Cannot divide by zero' }
        );
    });

    test('async operation resolves correctly', async () => {
        const result = await fetchUser(1);
        assert.equal(result.id, 1);
        assert.ok(result.name);
    });
});
# Run all tests
node --test

# Run a specific test file
node --test test/app.test.js

# Watch mode - re-run on file changes
node --test --watch

# With coverage (Node.js 22+)
node --test --experimental-test-coverage

Prülliste vor der Produktion

Gehen Sie diese Liste durch, bevor Sie Ihre Node.js-Anwendung live schalten:

  • NODE_ENV=production ist gesetzt – dadurch werden Leistungsoptimierungen in Express und anderen Bibliotheken aktiviert
  • Jede **Umgebungsvariable**, die Ihre Anwendung benötigt, existiert auf dem Server selbst und nicht nur in Ihrer lokalen .env-Datei
  • Es wird npm ci --omit=dev statt npm install ausgeführt, sodass nur die für die Produktion notwendigen Abhängigkeiten installiert werden
  • Die **Lockdatei** (package-lock.json oder pnpm-lock.yaml) wird in Git eingetragen – das Auslassen dieser Schritt kann dazu führen, dass CI/CD andere Abhängigkeitsversionen verwendet als bei Ihren Tests
  • Es gibt eine **sanfte Herunterfahrt**-Logik, bei der sowohl SIGTERM als auch SIGINT ordnungsgemäß behandelt werden
  • Es ist eine **Fehlerüberwachung** implementiert – die Ereignisse unhandledRejection und uncaughtException werden protokolliert und lösen Alarme aus
  • PM2 Startup ist so konfiguriert, dass die Anwendung nach einem Server-Neustart automatisch wieder gestartet wird
  • Rate Limiting ist aktiv, um Ihre API vor Missbrauch zu schützen
  • Ein Health-Check-Endpoint ist verfügbar, da Load Balancer und Uptime-Monitore davon abhängen
  • Zusammenfassung

    Es ist nicht notwendig, sich alles in diesem Leitfaden auf einmal einzuprägen. Speichern Sie ihn als Favoriten, kehren Sie immer wieder dorthin zurück, wenn Ihnen ein Befehl entfällt – mit der Zeit wird der Arbeitsablauf mühelos vertraut sein.

    KI-Tools sind hervorragend darin, Code zu generieren und ganze Projekte in dieser Entwicklungsphase zu erstellen – doch wenn Sie mitten in der Nacht mit einem defekten Produktivserver konfrontiert sind, hilft wirklich nur das souveräne Wissen um Ihre Tools. Kein Ausprobieren und Fehlermachen. Keine Panik.

    Konzentrieren Sie sich zunächst auf die Teile, an denen Sie ständig arbeiten werden: Paketmanager, Umgebungsvariablen und PM2. Alles Weitere wird sich von selbst ergeben, sobald Sie es benötigen.