Канцэнтрацыя каманд Node.js для локальных сервераў развіцця і сервераў прыменнення
Справака з командамі, якую можна сканаваць, яка раскрывае карыстоўванне версіямі Node.js, менеджэрамі пакетаў, налажванне сяродавысці, адлучэнне бягаючых працоў, PM2 і развёртванне Linux без перыяда выключэння.
Крыніцы: Node.js Cheatsheet — Essential Commands for Developers and Vibe Coders in 2026
nodejs
Кодаванне за дапамою ШІ зменіла спосаб стварэння проектаў. Вы описваеце бажаны рэзультат, а дапаможнік ШІ генеруе код, і за калькі хвілі у вас ўжо ёсць працюючы продукт. Аднак існуе момент, які ніякі дапаможнік не можа для вас адмахнуць — калі вы дывіцеся у вікно тэрміналу і патрабаваеце знання точнага команды, якую трэба ввести.
Можа, развертанне зламаецца на удаленам серверы. Можа, інсталляцыя не выйдзе на паўпацёку. Можа, зменныя сераўісу адмовяюцца чытацца, або процес згінуе без залічэння корыстных следаў. У такіх ситуацыях вы не хочаце шукаць у сторонніх дасведчэннях — вы хочаце швыраг пошук, які можна прасканаваць за секунды.
Гэта мета гэтага падрабніку: кампактныя інструкцыі па командах Node.js для двух сцэнарыяў — роботы на вашай локальной машыне і керавання серверам у працэсе вырабніцтва. Кожная команда супакоўвана кароткай адметкаю пра тое, калі яна є правым інструментам.
Запуск Node.js
Пачатакніце з асунутоўных вам основ, якія трэба знаты без двойных раздумоў:
# 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
Корыстныя флагі 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
Калектываванне версій Node.js — NVM
Для тых, хто адмахваецца колькома проектамі, кожны з якіх выкарыстоўвае іншую версію Node.js, nvm (Node Version Manager) стае не проста зручнасцю, а неабходнасцю.
# 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
Менеджеры пакетаў — npm, yarn і pnpm
Выбір менеджера пакетаў — гэта не проста стылістычны выбар; кожны варыянт мае своія сутэчкі.
Да 2026 года pnpm стаў разумным стандартам для большасці команд. Ён шыбкаа інсталюецца, эфектыва викорыстоўвае прастор на дыску, ухіляецца ад проблемы фантомных залежнасцей і прадае найэфектывнейшыя інструменты для манорепо. Падтрымка інструментаў таксама паднялася — фреймворкі на кшталт Next.js, Nuxt і SvelteKit чыста працуюць з pnpm.
Адзінако, які з іх падзе лепшая, залежыць ад вашай ситуацыі:
- npm — ўключаецца разам з Node.js за змовай, працюе ў будзь-якіх месцах, являецца надзеямым выборам для індывідуальных проектаў і пакетаў з адкрытым кодам
- yarn — падходзіць для вялікіх монорепозітарыёў у корпаратыўным масштабе, ў частнасці калі выкарыстоўваецца разам з Plug'n'Play (PnP)
- pnpm — найшырэйшы і найэфектывнейшы па выкарыстоўванню прастору варыянт, і ўзначальны выбор для працоўных наладак і монорепозітарыёў у 2026 годзе
Основныя каманды — усе трое менеджэраў пакетаў адночасна
# 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 — Найбольш неабходныя часткі
{
"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"
}
Аудыт і безпека
# 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
Зменныя сяродавішча
Зменныя сяродавішча дазволяюць вам раздзеляць наладкі межы розработкай і працоўным режымам. Штодзе адважвацца не кэдаваць секретныя даны, такія як ключы API або адресы база дадзенаў, у файлах коду.
# 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
У вашам коде на 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);
}
}
Система модуляў — CommonJS протыва ES Modules
Node.js яшчэ падтрымлеў два форматы модуляў, але новыя проекты должны выбіраць ES Modules, так как гэта савременны стандарт, які выкарыстоўваецца і ў браузерах.
// 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');
Сістэма файлаў — Аперацыі, якія вы будете вжываць найчэйш
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-сервер — Вбудованы, не трэба фреймворка
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}`);
});
Калектываванне процэсаў
// 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
Адлагоджэнне
# 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
У вашам коде:
// 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 — Калектывавальнік процэсаў для прымення
PM2 — это інструмент, які викорыстоўваецца для запуску Node.js у прымення. Ён автаматычна пачынае працу вашага дапрыемства пасля збою аб перезапуску сервера, і можа масштабавацца па колькісці ядоў CPU практычна без дадатковай налады.
# 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
Размешчэнне на серверы Linux
Ўжае паследованне дзеянняў, якія трэба выконваць пад час першага настаўлення Node.js на VPS або системе 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
Апдэйт размешчання без перыяда недзеяння
# 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, якія вы насправдзе будете вжываць пад час тыямування 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 і .nvmrc — два маленькія файлы, якія маюць значэнне
Этыя два файлы настаўлення можу здавацца простымі, але яны маюць вялікое значэнне, калі вы працуеце з командай.
# .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
Тэставанне — вбудованы запускчык тэстаў у Node.js
Пачынаючы з Node.js 20, запускчык тэстаў ўключаны ў сам рантайм. Для простых набораў тэстаў вы можете зовсама не інсталаваць Jest або Mocha.
// 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
Чакліст перед выпускам у працэўную среду
Пераканайцеся, што вы выпалнілі гэты чакліст, прытымкуючы вашае дзеўерс Node.js у працэўную среду:
- Установлена значэнне
NODE_ENV=production— гэта актывае оптымізацыю працысоў у Express і іншых бібліятэках - Кожная зменна аптэкі, якая патрэбная вашам прыему, існуе на самам серверы, а не толькі ў вашым локальным файле
.env - Вы выканалі
npm ci --omit=devзаместnpm install, таму інсталююцься толькі залежнасці для рэжыму production - Файл блокавання (
package-lock.jsonабоpnpm-lock.yaml) заносіцца у git — адказаўванне ад гэтага можа дазволіць системам CI/CD выкарыстоўваць іншыя версіі залежнасцей, чым вы тэставалі - Існуе логіка гракцыязнае завершэння працы, пры чым правільна обрабоўваюцца сигналы SIGTERM і SIGINT
- Установлена нагляд за аблыкамі — запісваюцься здарэння
unhandledRejectionіuncaughtException, якія таксама спрычыняюць апавешчэння
Заключныя меркі
Няма прычыны запамятаваць усё з гэтага карточку за адну момент. Дадзіце яй пазначку, вярніцеся кожны раз, калі ўскочыць команда, і з часам процес работы стане прывычным без дапамогі.
Інструменты AI чудова падходзяць для стварэння коду і будавання цэлых проектаў у гэтым фазе кодавання, але калі вы стаўляецеся да зламанага сервера ў палові ночы, насправды дапамагае тое, калі вы чытна ведаеце своі інструменты. Не пробаванняя і памылкі. Не паніка.
Спачатку зусім сконцентруйцеся на тых элементах, якія вы будетэце часта адчынваць: менеджеры пакетаў, зменныя сераўісу і PM2. Усе інша будзе стаць на свае месца, калі гэта будзе неабходна.