Referencja poleceń Node.js dla serwerów lokalnych i produkcyjnych
Przewodnik komend do skanowania, obejmujący zarządzanie wersjami Node.js, menedżery pakietów, konfigurację środowiska, debugowanie, PM2 oraz wdrażanie systemu Linux bez przerwy w działaniu.
Źródła: Node.js Cheatsheet — Essential Commands for Developers and Vibe Coders in 2026
nodejs
Kodowanie wspomagane przez sztuczną inteligencję zmieniło sposób tworzenia projektów. Opisujesz pożądany wynik, a asystent AI generuje kod, dzięki czemu w ciągu kilku minut masz już coś, co działa. Istnieje jednak sytuacja, której żaden asystent nie może za ciebie rozwiązać — gdy patrzysz na okno terminala i musisz wiedzieć dokładną komendę do wpisania.
Może dojść do awarii podczas rozgłoszenia na serwerze zdalnym. Może instalacja zawieść w połowie procesu. Może zmienne środowiskowe odmówić załadunku albo proces zakończyć się bez pozostawienia przydatnego śladu wywołań. W takich przypadkach nie chcesz przeglądać stron dokumentacji — potrzebujesz szybkiego sposobu wyszukiwania, który można przejrzeć w kilka sekund.
Taki jest cel tego przewodnika: zwięzły poradnik dotyczący poleceń Node.js przeznaczonych do dwóch zastosowań — pracy na lokalnym komputerze oraz zarządzania serwerem produkcyjnym. Każda komenda jest opatrzona krótką informacją o tym, w jakiej sytuacji jest odpowiednim narzędziem.
Zapусk Node.js
Zacznij od podstaw, które powinieneś znać bez dalszych rozważań:
# 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
Przydatne flagi CLI
# 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
Zarządzanie wersjami Node.js — NVM
Dla osób pracujących nad kilkoma projektami, z których każdy wymaga innej wersji Node.js, nvm (Node Version Manager) staje się koniecznością, a nie tylko udogodnieniem.
# 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
Menedżery pakietów — npm, yarn i pnpm
Wybór menedżera pakietów to coś więcej niż kwestia preferencji stylistycznych — każda opcja wiąże się z rzeczywistymi kompromisami.
Wchodząc w rok 2026, pnpm stał się rozsądnym standardem dla większości zespołów. Instaluje się szybko, efektywnie wykorzystuje przestrzeń dyskową, unika problemu pozornych zależności i oferuje najlepsze narzędzia do zarządzania monorepo. Podpora dla tych narzędzi również się rozwinęła — frameworki takie jak Next.js, Nuxt i SvelteKit działają bez problemów na pnpm.
Mimo to to, który narzędzie będzie najlepsze, zależy od Twojej sytuacji:
- npm — domyślnie dostępny wraz z Node.js, działa wszędzie, to niezawodny wybór dla projektów indywidualnych i pakietów otwartego oprogramowania
- yarn — doskonale sprawdza się w dużych monorepoach na skalę przedsiębiorstw, szczególnie w połączeniu z Plug'n'Play (PnP)
- pnpm — najszybsza i najbardziej efektywna pod względem przechowywania opcja, preferowana w środowiskach produkcyjnych i monorepoach w 2026 roku
Kluczowe polecenia — wszystkie trzy menedżery pakietów obok siebie
# 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 — najważniejsze elementy
{
"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"
}
Audyt i bezpieczeństwo
# 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
Zmienne środowiskowe
Zmienne środowiskowe umożliwiają oddzielenie konfiguracji pomiędzy środowiskiem rozwojowym a produkcyjnym. Unikaj wstawiania haseł takich jak klucze API czy adresy bazy danych bezpośrednio do plików źródłowych.
# 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
Wewnątrz kodu Node.js:
// 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);
}
}
System modułów — CommonJS kontra ES Modules
Node.js nadal obsługuje dwa formaty modułów, ale nowe projekty powinny domyślnie używać ES Modules, ponieważ jest to nowoczesny standard wspólny z przeglądarkami.
// 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');
System plików — Najczęściej używane operacje
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'
Serwer HTTP — Wbudowany, bez konieczności frameworka
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}`);
});
Zarządzanie procesami
// 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
Debugowanie
# 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
W twoim kodzie:
// 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 — Menedżer procesów do środowiska produkcyjnego
PM2 to narzędzie preferowane do uruchamiania Node.js w środowisku produkcyjnym. Automatycznie restartuje aplikację po awariach lub ponownym uruchomieniu serwera i może skalować się na różne rdzenie CPU przy niemal żadnej konfiguracji.
# 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
Rozwijanie na serwerze Linux
Oto sekwencja kroków, których należy przestrzegać podczas pierwszego instalowania Node.js na VPS lub maszynie Linux.
# 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
Aktualizacja aplikacji bez przerwy w działaniu
# 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
Polecenia Linux, których faktycznie użyjesz podczas konserwacji Node.js
# 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 i .nvmrc — dwa małe pliki o dużym znaczeniu
Te dwa pliki konfiguracyjne mogą wydawać się błahe, ale stają się bardzo ważne, gdy pracujesz z zespołem.
# .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
Testowanie — wbudowany narzędzie do testowania w Node.js
Począwszy od Node.js 20, narzędzie do testowania jest dostarczane razem z samym środowiskiem wykonawczym. W przypadku prostych zestawów testowych można całkowicie pominąć instalację Jest lub Mochi.
// 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
Lista sprawdzania przed wdrożeniem do produkcji
Przejrzyj tę listę przed wdrożeniem swojej aplikacji Node.js do środowiska produkcyjnego:
- Zostawiono ustawienie
NODE_ENV=production— to włącza optymalizacje wydajnościowe w Express i innych bibliotekach - Każda zmienna środowiskowa potrzebna przez twoją aplikację istnieje na samym serwerze, a nie tylko w lokalnym pliku
.env - Uruchamiasz
npm ci --omit=devzamiastnpm install, więc instalowane są tylko zależności przeznaczone do produkcji - Plik blokujący (
package-lock.jsonlubpnpm-lock.yaml) jest dodawany do repozytorium git — pominięcie tego może spowodować, że CI/CD użyje innych wersji zależności niż te, które przetestowałeś - Zastosowano logikę gracjalnego wyłączania, przy czym zarówno sygnały SIGTERM, jak i SIGINT są prawidłowo obsługiwane
- Nadzór nad błędami jest wdrożony — zdarzenia
unhandledRejectioniuncaughtExceptionsą rejestrowane i powodują wyświetlanie alertów
Podsumowanie
Nie musisz zapamiętywać wszystkiego z tego przewodnika za jednym razem. Zapisz go jako zakładkę, wracaj do niego wtedy, gdy zapomnisz jakiejś komendy — z czasem proces pracy stanie się naturalny i nie będzie wymagał wysiłku.
Narzędzia AI doskonale radzą sobie z generowaniem kodu i tworzeniem całych projektów w tej fazie programowania, w której się znajdujemy — ale gdy w środku nocy masz do czynienia z uszkodzonym serwerem produkcyjnym, naprawdę pomaga znajomość narzędzi na pamięć. Nie próby i błędy. Ani panika.
Najpierw skup się na elementach, których będziesz często używać: menedżerach pakietów, zmiennych środowiskowych oraz PM2. Wszystko inne ułoży się samo w miarę potrzeby.