С чего начать
REPL и запуск скриптов
REPL (Read-Eval-Print Loop) — интерактивная оболочка для экспериментов с кодом Node.js. Используйте node --watch для авто-перезапуска при разработке. ES-модули требуют type:module в package.json или расширения .mjs.
# start the REPL (interactive shell)
node
# run a script
node app.js
# run with ES modules (type: module in package.json)
node --input-type=module app.js
# execute inline code
node -e "console.log(process.version)"
# watch mode (auto-restart on change)
node --watch app.jsВерсия и флаги рантайма
node --version печатает версию рантайма. --trace-warnings показывает стек вызовов для предупреждений. NODE_OPTIONS — одна переменная окружения с CLI-флагами, удобна в контейнерах и npm-скриптах. --inspect открывает отладчик Chrome DevTools.
# check version
node --version # v20.11.0
node -p "process.versions.v8"
# enable warning stack traces
node --trace-warnings app.js
# pass NODE_OPTIONS (max ~128KB string)
NODE_OPTIONS="--max-old-space-size=4096" node app.js
# inspect memory usage at runtime
node --inspect app.jspackage.json и инициализация проекта
npm init создаёт package.json. Поле "type" определяет систему модулей по умолчанию: "module" включает синтаксис ES-модулей в .js-файлах, "commonjs" (по умолчанию) сохраняет require/module.exports. "main" — точка входа при подключении пакета.
# scaffold a project (answer prompts)
npm init
# non-interactive defaults
npm init -y
# "type" controls module system
# "commonjs" (default) -> require/module.exports
# "module" -> import/export
{
"name": "my-app",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"scripts": { "start": "node index.js" }
}CommonJS против ES-модулей
Node поддерживает две системы модулей. CommonJS (require/module.exports) синхронен и исторически был по умолчанию. ES-модули (import/export) — современный стандарт. Расширение файла (.mjs/.cjs) или поле "type" в package.json определяет, какой парсер используется для .js.
# CommonJS (.cjs or type:commonjs) ----
const fs = require('fs'); // import
module.exports = { greet: () => 'hi' }; // export
# ES Modules (.mjs or type:module) -------
import fs from 'fs'; // import
export function greet() { return 'hi'; } // named export
export default { greet }; // default export
# .mjs is always ESM, .cjs is always CJS
node file.mjs # forced ESM
node file.cjs # forced CJSГлобальные объекты
Node даёт глобальные process, console, Buffer и таймеры без импортов. __dirname и __filename существуют только в CommonJS — в ES-модулях используйте import.meta.url. global — корнев ой объект области видимости (как window в браузерах).
# available everywhere, no import needed
global; // global namespace object
process; // env, argv, stdin/stdout
console; // log, error, warn, table
setTimeout; // schedule a callback
setInterval; // schedule repeating callback
Buffer; // binary data (Uint8Array)
queueMicrotask;// schedule microtask
structuredClone; // deep clone
# CommonJS-only globals (not in ESM)
__dirname; // current directory
__filename; // current file pathИсполняемые скрипты (shebang)
Строка shebang (#!/usr/bin/env node) позволяет запускать файл как самостоятельную команду в Unix. После chmod +x запускайте ./cli.js напрямую. Поле "bin" в package.json сопоставляет имя команды скрипту; оно используется CLI-инструментами, опубликованными в npm, чтобы глобальная установка предоставляла команду.
#!/usr/bin/env node
// cli.js - make a file directly runnable
const name = process.argv[2] || 'world';
console.log(`Hello, ${name}!`);
# make it executable (Unix) and run directly
chmod +x cli.js
./cli.js Alice # Hello, Alice!
# or wire it up in package.json
{
"bin": { "mycli": "./cli.js" }
}Система модулей
require и exports в CommonJS
require() синхронно загружает CommonJS-модуль и возвращает его module.exports. require разрешает относительные пути (./, ../), встроенные модули (fs) и node_modules. Всегда присваивайте module.exports (а не exports), когда заменяете экспорт целиком: изначально exports — лишь псевдоним module.exports.
// math.js
function add(a, b) { return a + b; }
const PI = 3.14;
// export via module.exports
module.exports = { add, PI };
// or: exports.add = add; exports.PI = PI;
// app.js
const math = require('./math'); // .js optional
console.log(math.add(1, 2)); // 3
console.log(math.PI); // 3.14
// destructuring
const { add } = require('./math');
console.log(add(5, 7)); // 12import/export в ES-модулях
ES-модули используют статические import/export — привязки живые и поднимаются (hoisting). Экспорт по умолчанию импортируется под любым именем (без скобок); именованные экспорты требуют скобок с совпадающими именами. import * as создаёт объект пространства имён. ESM асинхронен по устройству и является современным стандартом.
// math.mjs (or type:module)
export function add(a, b) { return a + b; }
export const PI = 3.14;
export default function square(x) { return x * x; }
// app.mjs
import square, { add, PI } from './math.mjs';
console.log(add(1, 2)); // 3
console.log(square(5)); // 25
// import all as namespace
import * as math from './math.mjs';
console.log(math.PI); // 3.14Динамический import()
import() — динамический асинхронный импорт, доступный и в CJS, и в ESM. Он возвращает Promise, разрешающийся в пространство имён модуля, что позволяет ленивую загрузку и условные импорты: отлично для сокращения времени запуска или загрузки необязательных функций. Используйте его и для разделения кода на серверах.
// dynamic import returns a Promise
async function loadPlugin(name) {
const mod = await import(`./plugins/${name}.mjs`);
return mod.default;
}
// lazy-load heavy modules on demand
if (needPdf) {
const { exportPdf } = await import('./pdf.mjs');
exportPdf(data);
}
// works in both CommonJS and ESM
import('./optional.mjs')
.then(mod => mod.run())
.catch(err => console.error('load failed', err));Встроенные модули
Node поставляется с десятками встроенных модулей — npm install не нужен. Большинство предоставляют callback-API; многие также имеют promise-варианты по пути 'module/promises' (fs/promises, dns/promises, stream/promises). require('module') (без ./) сначала ищет встроенные модули, затем в node_modules.
// core modules - no install, just require/import
const fs = require('fs'); // file system
const path = require('path'); // path handling
const http = require('http'); // HTTP server/client
const os = require('os'); // OS info
const crypto = require('crypto'); // hashing/encryption
const { EventEmitter } = require('events');
const { Buffer } = require('buffer');
const stream = require('stream'); // streams
const net = require('net'); // TCP
const child_process = require('child_process');
// some are promise-based (Node 10+)
const fsp = require('fs/promises'); // async/await fsКеш модулей и циклические зависимости
require() кеширует модули по разрешённому пути, поэтому один и тот же код выполняется раз, а экспорты переиспользуются. Циклические зависимости работают, но первый загруженный модуль видит неполный (частичный) объект exports второго — проектируйте с учётом этого. Удаляйте require.cache для горячей перезагрузки при разработке.
// modules are cached after first load
// a.js
require('./b'); // b loads, sets module.exports
const b = require('./b'); // returns cached b (same object)
console.log(b === require('./b')); // true
// circular dependency: a -> b -> a
// a.js: const b = require('./b'); b.f();
// b.js: const a = require('./a'); // a is PARTIAL here!
// module.exports = { f: () => a.x };
// inspect the cache
console.log(require.cache); // map of loaded modules
delete require.cache[require.resolve('./b')]; // force reload__dirname и import.meta.url
__dirname и __filename — глобальные переменные только CommonJS, дающие путь текущей папки и файла. В ES-модулях таких глобалов нет — получайте их из import.meta.url через fileURLToPath. import.meta.url — это file:// URL текущего модуля и замена __filename в ESM.
// CommonJS - synchronous path globals
console.log(__dirname); // /app/src
console.log(__filename); // /app/src/index.js
// ES Modules - no __dirname, use import.meta
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const dataPath = join(__dirname, 'data.json');
// import.meta also carries the module URL
console.log(import.meta.url); // file:///app/src/index.mjsnpm и pnpm
npm init и package.json
npm init создаёт package.json. -y пропускает вопросы, используя значения по умолчанию. npm set сохраняет конфигурацию в ~/.npmrc для будущих инициализаций. Скоуп-пакеты (@org/name) полезны для организаций и предотвращения коллизий имён в реестре.
# create package.json interactively
npm init
# accept all defaults
npm init -y
# pnpm equivalent
pnpm init
# set author/license globally
npm set init-author-name "Alice"
npm set init-license MIT
# scope packages with @username
npm init --scope=@myorgУстановка зависимостей
npm install (без аргументов) ставит все перечисленные зависимости. С именем пакета добавляет его в package.json. --save-dev помещает в devDependencies (инструменты тестов и сборки, не поставляются). ^ разрешает обновления minor+patch, ~ — только patch. -g устанавливает CLI-инструменты глобально.
# install everything in package.json
npm install # alias: npm i
pnpm install # alias: pnpm i
# add a runtime dependency -> dependencies
npm install express
pnpm add express
# add a dev-only dependency -> devDependencies
npm install --save-dev jest # npm i -D jest
pnpm add -D jest
# install a specific version
npm install [email protected]
npm install lodash@^4.17.0 # caret: 4.x
npm install lodash@~4.17.0 # tilde: 4.17.x
# global install (CLI tools)
npm install -g pm2
pnpm add -g pm2npm-скрипты
Скрипты в package.json запускаются через npm run <name>. start и test особенны (npm start / npm test). Хуки pre/post (pretest, postbuild) выполняются автоматически. Используйте --, чтобы передать аргументы нижележащей команде. pnpm позволяет опускать слово "run" для пользовательских скриптов.
// package.json
{
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "jest",
"build": "tsc && vite build"
}
}
# run a script
npm run dev # npm run-script dev
pnpm dev # pnpm has no "run" requirement
# "start" and "test" have shortcuts
npm start
npm test
# pre/post hooks run automatically
// "pretest": "npm run lint",
// "postbuild": "npm run deploy"
# pass extra args with --
npm run build -- --mode productionnpx и pnpm dlx
npx запускает бинарник пакета без глобальной установки: скачивает, выполняет и удаляет. Идеально для генераторов (create-vite) и запуска инструментов из локального node_modules/.bin. --yes пропускает подтверждение установки. pnpm dlx — аналог в pnpm.
# run a one-off command without installing globally
npx create-vite my-app
npx cowsay "hello"
# pin a version
npx prettier@3 --write .
# pnpm equivalent
pnpm dlx create-vite my-app
# execute a local bin from node_modules
npx jest # runs ./node_modules/.bin/jest
# never prompt, always download latest
npx --yes create-react-app my-appВерсионирование и lock-файлы
SemVer: MAJOR для ломающих изменений, MINOR для новых возможностей, PATCH для исправлений. ^ (каретка) — значение по умолчанию в npm, разрешает minor+patch; ~ (тильда) — только patch. Lock-файлы (package-lock.json) фиксируют всё дерево зависимостей для воспроизводимых установок — в CI используйте npm ci ради скорости и безопасности.
# semantic versioning: MAJOR.MINOR.PATCH
# 1.4.2 -> 1:breaking 4:feature 2:fix
"^1.4.2" # >=1.4.2 <2.0.0 (caret, default)
"~1.4.2" # >=1.4.2 <1.5.0 (tilde)
"1.4.2" # exact 1.4.2
">=1.4.0 <2.0.0" # range
# lockfiles pin the installed tree
npm install # writes/updates package-lock.json
pnpm install # writes pnpm-lock.yaml
yarn install # writes yarn.lock
# install exactly as locked (CI)
npm ci # clean install from lockfile
# find outdated deps
npm outdated
npm update # update within ^ rangesПубликация и жизненный цикл
npm publish загружает пакет в реестр. npm version повышает версию, создаёт git-тег и коммит. Хуки жизненного цикла (prepublishOnly, postpublish) автоматизируют сборку и тесты при релизе. Отмена публикации разрешена только в течение 72 часов — для старых версий предпочитайте npm deprecate.
# login once
npm login
# publish to the registry
npm publish
npm publish --access public # scoped default restricted
# bump version (updates package.json + tag + commit)
npm version patch # 1.0.0 -> 1.0.1
npm version minor # 1.0.0 -> 1.1.0
npm version major # 1.0.0 -> 2.0.0
# lifecycle scripts (in package.json)
// "prepublishOnly": "npm test && npm run build",
// "prepublish": "npm run build",
// "postpublish": "git push --tags"
# unpublish within 72h
npm unpublish [email protected]Файловая система (fs)
Чтение файлов
fs предлагает синхронные (readFileSync), callback- (readFile) и promise-API (readFile из fs/promises). Синхронные вызовы блокируют цикл событий — избегайте их на серверах. fs/promises — современный выбор для async/await. Без указания кодировки readFile возвращает Buffer.
const fs = require('fs');
// synchronous (blocks the event loop)
const text = fs.readFileSync('data.txt', 'utf8');
const buf = fs.readFileSync('image.png'); // Buffer
// asynchronous with callback (error-first)
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) return console.error(err);
console.log(data);
});
// async with fs/promises (preferred)
const fsp = require('fs/promises');
async function read() {
const text = await fsp.readFile('data.txt', 'utf8');
return text;
}Запись файлов
writeFile по умолчанию заменяет файл целиком. Опция flag меняет поведение: 'a' дописывает, 'wx' падает (EEXIST), если файл уже существует, — полезно для атомарного создания. JSON нужно сначала сериализовать в строку. Синхронная запись блокирует; предпочитайте fs/promises.
const fs = require('fs');
const fsp = require('fs/promises');
// sync
fs.writeFileSync('out.txt', 'hello');
// async callback
fs.writeFile('log.txt', 'line1\n', err => {
if (err) throw err;
});
// promise
await fsp.writeFile('config.json', JSON.stringify(cfg, null, 2));
// flags: 'w' write (default), 'a' append, 'wx' fail if exists
await fsp.writeFile('new.txt', 'x', { flag: 'wx' }); // throws if existsКаталоги
mkdir с { recursive: true } имитирует mkdir -p. readdir перечисляет записи; { withFileTypes: true } возвращает объекты Dirent, чьи isDirectory()/isFile() избавляют от лишних stat-вызовов. fsp.rm с recursive+force заменяет rmdir для непустых каталогов (Node 14+).
const fsp = require('fs/promises');
// create (recursive like mkdir -p)
await fsp.mkdir('a/b/c', { recursive: true });
// list entries
const entries = await fsp.readdir('.');
// ['app.js', 'data', 'package.json']
// list with type info
const detailed = await fsp.readdir('.', { withFileTypes: true });
detailed.forEach(e => console.log(e.name, e.isDirectory()));
// remove
await fsp.rmdir('empty'); // empty dir only
await fsp.rm('folder', { recursive: true, force: true }); // rm -rf
// sync versions exist too: mkdirSync, readdirSync, rmSyncСтатистика и метаданные файлов
stat() возвращает объект Stats с size, mtime и помощн иками типа. Не используйте fs.exists (устарел); применяйте access() в try/catch для проверки существования без гонок, хотя открытие файла напрямую надёжнее. fsWatch генерирует события изменений, но может вести себя неодинаково на разных платформах.
const fsp = require('fs/promises');
const stats = await fsp.stat('data.txt');
stats.isFile(); // true
stats.isDirectory(); // false
stats.size; // bytes
stats.mtime; // Date modified
stats.birthtime; // Date created
stats.mode; // permission bits
// check existence (avoid existsSync for races)
try {
await fsp.access('config.json');
console.log('exists');
} catch {
console.log('missing');
}
// watch for changes
const watcher = fs.watch('.');
watcher.on('change', (eventType, filename) => {});API fs.promises
fs/promises (Node 10+) даёт promise-версии всех методов fs, идеальные для async/await. opendir() возвращает асинхронный итератор для обхода каталогов с экономией памяти. Сочетайте с path.join для переносимых путей. Все методы бросают исключения при ошибке — оборачивайте в try/catch.
const fsp = require('fs/promises');
const path = require('path');
// full async/await file operations
async function loadConfig() {
const file = path.join(__dirname, 'config.json');
const raw = await fsp.readFile(file, 'utf8');
return JSON.parse(raw);
}
async function saveConfig(cfg) {
const file = path.join(__dirname, 'config.json');
await fsp.writeFile(file, JSON.stringify(cfg, null, 2));
}
// iterate directory tree
for await (const entry of await fsp.opendir('.')) {
console.log(entry.name);
}Дозапись, переименование, удаление
appendFile добавляет содержимое в конец (создаёт файл, если его нет). rename атомарен в пределах одной файловой системы и используется для перемещения. unlink удаляет файл. copyFile копирует содержимое; fsp.cp (Node 16+) рекурсивно обрабатывает каталоги. truncate изменяет размер файла до заданной длины.
const fsp = require('fs/promises');
// append to a file (creates if missing)
await fsp.appendFile('log.txt', new Date() + ' started\n');
// atomic rename (also for moving)
await fsp.rename('old.txt', 'new.txt');
// move across dirs
await fsp.rename('a/x.txt', 'b/x.txt');
// delete a file
await fsp.unlink('temp.txt');
// copy
await fsp.copyFile('src.txt', 'dest.txt');
// or fsp.cp('src', 'dest', { recursive: true })
// truncate to a length
await fsp.truncate('data.bin', 1024);Работа с путями
path.join и path.resolve
path.join соединяет сегменты через разделитель платформы и нормализует результат. path.resolve строит абсолютный путь, начиная от process.cwd(); абсолютный сегмент отбрасывает предыдущие. Всегда используйте path.join вместо конкатенации строк, чтобы пути работали в Windows и POSIX.
const path = require('path');
// join segments with the OS separator
path.join('src', 'utils', 'file.js');
// 'src/utils/file.js' (Linux) or 'src\utils\file.js' (Windows)
// resolve to an ABSOLUTE path (from cwd)
path.resolve('src', 'file.js');
// '/current/dir/src/file.js'
// resolve with absolute segment resets
path.resolve('/a', 'b', '/c', 'd'); // '/c/d'
// normalize '..' and '.' segments
path.normalize('a/b/../c/./d'); // 'a/c/d'
// never hardcode '/' — use path.join for portabilitydirname, basename, extname
dirname возвращает каталог, basename — имя файла (при желании без расширения), extname — последнее расширение (включая точку). Для составных расширений вроде .tar.gz возвращается только финальное .gz. Это чистые строковые операции без обращения к файловой системе.
const path = require('path');
const file = '/app/src/utils/helper.js';
path.dirname(file); // '/app/src/utils'
path.basename(file); // 'helper.js'
path.basename(file, '.js'); // 'helper' (strip ext)
path.extname(file); // '.js'
path.extname('archive.tar.gz'); // '.gz' (last ext)
// for the current file (CommonJS)
path.dirname(__filename); // current dir
path.basename(__filename); // current file namepath.parse и path.format
path.parse разбивает путь на root, dir, base, name и ext. path.format собирает их обратно. path.relative вычисляет относительный путь из одного каталога в другой. Вместе они делают манипуляции с путями декларативными, а не кропотливым нарезанием строк.
const path = require('path');
// decompose a path into parts
const p = path.parse('/app/src/helper.test.js');
// { root: '/', dir: '/app/src',
// base: 'helper.test.js', name: 'helper.test', ext: '.js' }
// rebuild from a parsed object
const rebuilt = path.format({
dir: '/app/dist',
name: 'bundle',
ext: '.min.js'
});
// '/app/dist/bundle.min.js'
// get the relative path from A to B
path.relative('/a/b/c', '/a/x'); // '../../x'Кросс-платформенные пути
path.sep и path.delimiter различаются по ОС. path.win32 и path.posix принудительно выбирают конкретный парсер независимо от хост-ОС — удобно при обработке путей с другой платформы. Используйте path.delimiter для переносимого разбора переменных окружения в стиле PATH вместо жёсткого ':' или ';'.
const path = require('path');
// platform-specific values
path.sep; // '/' (POSIX) or '\\' (Windows)
path.delimiter; // ':' (POSIX) or ';' (Windows)
// force a specific platform's behavior
path.win32.join('a', 'b'); // 'a\\b'
path.posix.join('a', 'b'); // 'a/b'
// parse PATH env var portably
process.env.PATH.split(path.delimiter).forEach(dir => {
console.log(dir);
});
// check if absolute
path.isAbsolute('/etc'); // true
path.isAbsolute('a/b'); // false
path.win32.isAbsolute('C:\\'); // trueFile URL и pathToFileURL
ES-модули идентифицируются file:// URL. Используйте url.pathToFileURL, чтобы превратить обычный путь в URL для динамического import(), и url.fileURLToPath для обратного преобразования. В ESM import.meta.url уже является file URL — конвертируйте его в путь через fileURLToPath, чтобы воспроизвести __filename.
const path = require('path');
const url = require('url');
// convert a path to a file:// URL (ESM import)
const fileUrl = url.pathToFileURL('/app/src/mod.mjs');
// URL { href: 'file:///app/src/mod.mjs' }
// and back
const p = url.fileURLToPath('file:///app/src/mod.mjs');
// '/app/src/mod.mjs'
// in ESM, import.meta.url is already a file URL
// convert to a normal path:
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);HTTP-сервер
Базовый HTTP-сервер
http.createServer возвращает сервер; callback обрабатывает каждый запрос. res.writeHead задаёт код статуса и заголовки, res.end отправляет тело и завершает ответ. listen() начинает принимать соединения на заданном порту. Один процесс Node обрабатывает множество параллельных запросов через цикл событий.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
// listen on a port
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
// or with a host and backlog
server.listen(3000, '127.0.0.1', 511, () => {});Запрос и ответ
req открывает method, url и headers; res позволяет задать statusCode/headers, затем write+end. res.end ОБЯЗАТЕЛЬНО нужно вызвать, чтобы завершить ответ. Для больших полезных нагрузок передавайте данные потоком через res.write или направьте Readable в res, чтобы не буферизовать всё в памяти.
const http = require('http');
http.createServer((req, res) => {
// request info
console.log(req.method); // 'GET'
console.log(req.url); // '/users?id=5'
console.log(req.headers); // { host, 'user-agent', ... }
// response helpers
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write('partial chunk\n');
res.end(JSON.stringify({ ok: true }));
}).listen(3000);
// streaming a large response
res.writeHead(200);
readStream.pipe(res); // pipe file -> responseМаршрутизация и разбор URL
В Node нет встроенного роутера: реализуйте его через if/else по req.method и req.url или используйте конструктор URL для разбора pathname и searchParams. Для реальных приложений берите Express или роутер фреймворка. Конструктору URL нужна база при разборе относительного req.url.
const http = require('http');
const { URL } = require('url');
http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
const path = url.pathname;
const q = url.searchParams.get('id');
if (req.method === 'GET' && path === '/') {
res.end('home');
} else if (path === '/users') {
res.end('users');
} else {
res.writeHead(404);
res.end('not found');
}
}).listen(3000);Обработка JSON и тела POST
Тела запросов приходят потоком — нужно собрать чанки перед разбором. Паттерн асинхронного итератора (for await of req) — современный подход. Всегда задавайте Content-Type: application/json, отвечая JSON. В продакшене ограничивайте размер тела, чтобы предотвратить исчерпание памяти.
const http = require('http');
http.createServer(async (req, res) => {
if (req.method === 'POST') {
// collect the streamed body
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const body = JSON.parse(Buffer.concat(chunks).toString());
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: body }));
}
}).listen(3000);
// test: curl -X POST localhost:3000 -d '{"a":1}'События сервера и ошибки
Сервер — это EventEmitter. Событие 'error' нужно обрабатывать: EADDRINUSE означает, что порт занят. 'connection' срабатывает на каждый клиентский сокет. Для корректного завершения слушайте SIGTERM/SIGINT и вызывайте server.close(), чтобы текущие запросы завершились до выхода процесса.
const server = http.createServer(handler);
server.on('listening', () => console.log('ready'));
server.on('connection', socket => console.log('client connected'));
server.on('error', err => {
if (err.code === 'EADDRINUSE') {
console.error('port 3000 already in use');
}
});
server.on('close', () => console.log('server closed'));
// graceful shutdown
process.on('SIGTERM', () => {
server.close(() => process.exit(0));
});
server.listen(3000);HTTPS и HTTP-клиент
https.createServer требует приватного ключа и сертификата (например, от Let's Encrypt). Для исходящих запросов в Node 18+ есть глобальный fetch() — предпочитайте его сырому callback-API http.get. fetch основан на промисах и поддерживает async/await, заголовки и потоки.
// HTTPS server (needs TLS certs)
const https = require('https');
const fs = require('fs');
https.createServer({
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}, handler).listen(443);
// HTTP client: simple GET
http.get('http://example.com', res => {
let data = '';
res.on('data', c => data += c);
res.on('end', () => console.log(data));
});
// modern fetch (Node 18+, global, promise-based)
const res = await fetch('https://api.example.com');
const json = await res.json();Основы Express
Настройка Express и Hello World
Express — самый популярный веб-фреймворк для Node. app.get регистрирует обработчик маршрута; res.send отправляет ответ (автоматически определяя Content-Type). app.listen запускает сервер. Express оборачивает HTTP-модуль Node, добавляя маршрутизацию, middleware и удобные помощники.
// install: npm install express
import express from 'express';
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(PORT, () => {
console.log(`Server on http://localhost:${PORT}`);
});Маршруты и параметры
Express сопоставляет HTTP-методы (get/post/put/delete) с путями. :id захватывает сегменты URL в req.params; req.query хранит значения строки запроса. app.route позволяет сцепить несколько методов для одного пути. Маршруты сопоставляются в порядке регистрации, поэтому определяйте специфичные маршруты раньше общих.
app.get('/users', (req, res) => res.send('list users'));
app.post('/users', (req, res) => res.send('create user'));
// URL parameters
app.get('/users/:id', (req, res) => {
res.send(`user ${req.params.id}`);
});
// query strings: /search?q=node
app.get('/search', (req, res) => {
res.send(`searching: ${req.query.q}`);
});
// chain handlers for one path
app.route('/book')
.get((req, res) => res.send('get book'))
.post((req, res) => res.send('add book'));Middleware
Middleware — функции, выполняемые в течение цикла запроса и получающие req, res и next. Вызовите next(), чтобы перейти к следующему обработчику. app.use монтирует middleware глобально или на префикс пути. Обработчик ошибок имеет 4 аргумента (первым err) и должен регистрироваться последним.
// middleware: (req, res, next) => {}
app.use(express.json()); // parse JSON bodies
app.use(express.static('public'));// serve static files
app.use((req, res, next) => { // custom logger
console.log(req.method, req.url);
next(); // pass control forward
});
// mounted on a path
app.use('/api', (req, res, next) => {
req.apiCall = true;
next();
});
// error-handling middleware (4 args)
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Server Error');
});Данные запроса
Express разбирает тела, только если смонтировано нужное middleware: express.json() для JSON, express.urlencoded() для форм, multer для загрузки файлов. req.params (сегменты URL), req.query (строка запроса) и req.body (разобранная нагрузка) — три основных источника данных запроса.
// JSON body (needs express.json() middleware)
app.post('/api', (req, res) => {
console.log(req.body); // parsed JSON object
});
// URL params and query
app.get('/u/:id', (req, res) => {
const { id } = req.params;
const { tab } = req.query;
});
// form data (urlencoded)
app.use(express.urlencoded({ extended: true }));
app.post('/form', (req, res) => res.json(req.body));
// file uploads: use multer middleware
// const upload = multer({ dest: 'uploads/' });
// app.post('/upload', upload.single('file'), handler);
// headers & cookies
req.headers['user-agent'];
req.cookies; // needs cookie-parserРаздача статики
express.static раздаёт файлы из каталога. Монтируйте несколько раз для резервного поведения или с префиксом пути. Опции вроде maxAge задают заголовки кеширования. Он автоматически определяет MIME-типы и поддерживает range-запросы для видео и аудио. Всегда используйте абсолютные пути, чтобы избежать багов, зависящих от cwd.
const path = require('path');
// serve files from /public at /
app.use(express.static('public'));
// GET /style.css -> public/style.css
// mount at a prefix
app.use('/static', express.static('public'));
// GET /static/style.css -> public/style.css
// multiple directories (fallthrough)
app.use(express.static('public'));
app.use(express.static('uploads'));
// absolute path + options
app.use(express.static(path.join(__dirname, 'public'), {
maxAge: '1d',
setHeaders: (res, filePath) => {
if (filePath.endsWith('.html')) res.setHeader('Cache-Control', 'no-cache');
}
}));Обработка ошибок и Router
Передайте ошибку в next(err) или выбросьте её внутри асинхронного обработчика, чтобы вызвать middleware обработки ошибок. Зарегистрируйте один центральный обработчик с 4 аргументами последним. express.Router() делает маршруты модульными: монтируйте их через app.use('/prefix', router), чтобы чисто собирать большой API.
// throw to jump to error middleware
app.get('/broken', (req, res, next) => {
const err = new Error('boom');
err.status = 400;
next(err); // or throw err (Express 4+)
});
// centralized error handler (last middleware)
app.use((err, req, res, next) => {
const status = err.status || 500;
res.status(status).json({ error: err.message });
});
// modular routing with express.Router()
const router = express.Router();
router.get('/', (req, res) => res.send('api root'));
router.get('/users', (req, res) => res.send('users'));
app.use('/api', router); // mount at /apiПотоки (Streams)
Readable-потоки
Readable-поток производит данные. В режиме flowing события 'data' выталкивают чанки автоматически; в paused вы вызываете read() явно. Всегда обрабатывайте 'error' — необработанные события ошибок роняют процесс. highWaterMark управляет размером внутреннего буфера.
const fs = require('fs');
// create a readable stream from a file
const rs = fs.createReadStream('big.log', { highWaterMark: 64 * 1024 });
// 'data' mode (flowing)
rs.on('data', chunk => {
console.log('got', chunk.length, 'bytes');
});
rs.on('end', () => console.log('done'));
rs.on('error', err => console.error(err));
// paused mode: pull on demand
rs.on('readable', () => {
let chunk;
while ((chunk = rs.read()) !== null) {
process(chunk);
}
});Writable-потоки
Writable-поток потребляет данные. write() возвращает false, когда внутренний буфер заполнен, — дождитесь события 'drain', прежде чем писать дальше, чтобы уважать backpressure. end() сигнализирует, что данных больше нет; 'finish' срабатывает после сброса всего. process.stdout сам является writable-потоком.
const fs = require('fs');
const ws = fs.createWriteStream('out.log');
// write returns false when the buffer is full (backpressure)
const ok = ws.write('line\n');
if (!ok) ws.once('drain', () => writeMore());
// signals completion
ws.end('final line\n');
ws.on('finish', () => console.log('all data flushed'));
ws.on('error', err => console.error(err));
// process.stdout is a writable stream
process.stdout.write('hello');pipe и pipeline
pipe() направляет Readable в Writable с автоматическим backpressure. stream.pipeline (предпочтительно версия из promises) сцепляет несколько потоков И корректно распространяет ошибки и очищает ресурсы: один .pipe() утекает ресурсами при ошибке посреди потока. Всегда предпочитайте pipeline ручным цепочкам .pipe().
const fs = require('fs');
const { pipeline } = require('stream/promises');
// pipe: readable -> writable (auto backpressure)
fs.createReadStream('in.txt')
.pipe(fs.createWriteStream('out.txt'));
// pipeline: chain transforms, with error handling
const { Transform } = require('stream');
const upper = new Transform({
transform(chunk, enc, cb) { cb(null, chunk.toString().toUpperCase()); }
});
await pipeline(
fs.createReadStream('in.txt'),
upper,
fs.createWriteStream('out.txt')
);
// pipeline rejects on error, unlike .pipe()Transform-потоки
Transform-поток читает вход, обрабатывает его и выдаёт преобразованный выход — идеален для разбора, сжатия или шифрования в конвейере. Реализуйте transform(chunk, enc, cb) и при необходимости flush(cb). objectMode позволяет передавать объекты вместо Buffer. zlib и crypto дают готовые трансформы.
const { Transform } = require('stream');
// a Transform is both Readable and Writable
const csvToJson = new Transform({
objectMode: false,
transform(chunk, encoding, callback) {
// convert each chunk
const lines = chunk.toString().trim().split('\n');
const json = lines.map(l => JSON.stringify(l.split(','))).join('\n');
callback(null, json + '\n');
},
flush(callback) {
callback(null, ']\n'); // finalize
}
});
process.stdin.pipe(csvToJson).pipe(process.stdout);
// built-in transforms: zlib, crypto streams
const { createGzip } = require('zlib');
fs.createReadStream('log').pipe(createGzip()).pipe(fs.createWriteStream('log.gz'));Режимы потоков и backpressure
Потоки переключаются между flowing и paused через pause()/resume(). Backpressure означает, что медленный потребитель сигнализирует производителю замедлиться: асинхронная итерация (for await) делает это автоматически, дожидаясь каждого чанка, — самый чистый современный паттерн. Всегда задавайте кодировку, чтобы получать строки вместо Buffer.
const rs = fs.createReadStream('huge.bin');
// switch between modes
rs.pause();
rs.resume();
rs.setEncoding('utf8');
// respect backpressure manually
function writeChunk(ws, data) {
if (!ws.write(data)) {
rs.pause();
ws.once('drain', () => rs.resume());
}
}
// async iteration (Node 10+) — cleanest pattern
async function consume() {
for await (const chunk of rs) {
await handle(chunk); // naturally respects backpressure
}
}
consume();Собственные потоки
Наследуйтесь от Readable/Writable/Duplex и реализуйте _read/_write или используйте более простой Readable.from() для уже имеющихся данных. push(null) сигнализирует конец потока. Duplex-потоки одновременно читаемые И записываемые независимо (как TCP-сокеты); Transform — это Duplex, где выход происходит из входа.
const { Readable, Writable, Duplex } = require('stream');
// custom Readable: generate a counter
const counter = new Readable({
read() {
if (++this._n > 10) this.push(null); // end
else this.push(String(this._n));
}
});
counter._n = 0;
counter.pipe(process.stdout);
// from an array / async iterable
Readable.from(['a', 'b', 'c']).pipe(process.stdout);
// a Duplex: both readable and writable (e.g. a socket)
class Echo extends Duplex {
_read() {}
_write(chunk, enc, cb) { this.push(chunk); cb(); }
}Buffer
Создание Buffer
Buffer.alloc создаёт буфер, заполненный нулями (безопасно). Buffer.allocUnsafe пропускает обнуление ради скорости, но может выдать старую память — используйте только если перезапишете каждый байт. Buffer.from конвертирует строки, массивы и буферы. Устаревший конструктор 'new Buffer()' не рекомендуется из-за проблем безопасности.
// allocate zeroed bytes (SAFE)
const b1 = Buffer.alloc(8); // <Buffer 00 00 00 00 00 00 00 00>
// allocate WITHOUT zeroing (faster, may contain old memory)
const b2 = Buffer.allocUnsafe(8); // random old data!
// from a string with encoding
const b3 = Buffer.from('hello', 'utf8');
// <Buffer 68 65 6c 6c 6f>
// from an array of bytes
const b4 = Buffer.from([0x48, 0x49]); // 'HI'
// from another buffer (copy)
const b5 = Buffer.from(b3);
// NEVER use new Buffer() — deprecated and unsafeЧтение и запись
Buffer хранит сырые байты. Используйте методы чтения/записи с явными размерами (UInt8/16/32) и порядком байтов (BE/LE). Big-endian — сетевой порядок байтов; little-endian распространён на x86. toString(encoding, start, end) декодирует байты в строку. Всегда передавайте смещение, чтобы не перезаписать предыдущие байты.
const buf = Buffer.alloc(8);
// write numeric values at an offset
buf.writeUInt8(255, 0); // 1 byte
buf.writeUInt16BE(0x1234, 1); // 2 bytes, big-endian
buf.writeInt32LE(1000, 3); // 4 bytes, little-endian
// read them back
buf.readUInt8(0); // 255
buf.readUInt16BE(1); // 0x1234
buf.readInt32LE(3); // 1000
// string read/write
buf.write('Hi', 0, 'utf8');
buf.toString('utf8', 0, 2); // 'Hi'Объединение и сравнение
Buffer.concat объединяет массив буферов (необязательная подсказка общей длины ускоряет работу). equals/compare сравнивают последовательности байтов; indexOf/includes находят подбуферы — полезно в бинарных протоколах. copy(target, targetStart, sourceStart, sourceEnd) копирует срез в другой буфер.
const a = Buffer.from('foo');
const b = Buffer.from('bar');
// concatenate buffers
const c = Buffer.concat([a, b]); // 'foobar'
Buffer.concat([a, b], 6); // total length hint
// compare
Buffer.compare(a, b); // -1 (a < b), 0, or 1
a.equals(b); // false
// find a sub-buffer
const big = Buffer.from('hello world');
big.indexOf(Buffer.from('world')); // 6
big.includes(Buffer.from('hello')); // true
// copy bytes
const target = Buffer.alloc(5);
big.copy(target, 0, 0, 5); // copy first 5 bytesКодировки
Кодировки отображают строки в байты и обратно. utf8 — по умолчанию для текста. base64/hex распространены для бинарных данных в тексте (data URL, хеши, транспорт). Buffer.byteLength даёт размер в байтах (многобайтные символы занимают больше одного байта в utf8) — используйте его при расчёте буферов, а не string.length.
const text = 'Hello, 世界';
// string -> buffer (encode)
const utf8 = Buffer.from(text, 'utf8');
const base64 = Buffer.from(text).toString('base64');
const hex = Buffer.from(text).toString('hex');
const latin1 = Buffer.from(text, 'latin1');
// buffer -> string (decode)
utf8.toString('utf8'); // 'Hello, 世界'
Buffer.from(base64, 'base64').toString('utf8');
Buffer.from(hex, 'hex').toString('utf8');
// common encodings: utf8, utf16le, latin1, ascii,
// base64, base64url, hex
Buffer.byteLength('世界', 'utf8'); // 6 bytes (not 2)Buffer и TypedArray
Buffer наследует Uint8Array, поэтому работает везде, где работают TypedArray. Buffer.from(arrayBuffer) разделяет память (без копии), но Buffer может быть срезом большего пулового ArrayBuffer, поэтому всегда учитывайте byteOffset/byteLength при создании представлений. Это позволяет сочетать API Buffer с DataView для тонкого числового доступа.
// Buffer is a subclass of Uint8Array
const buf = Buffer.from([1, 2, 3]);
buf instanceof Uint8Array; // true
// share memory with TypedArrays without copying
const u8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
view.getInt32(0);
// Buffer from an ArrayBuffer
const ab = new ArrayBuffer(8);
const buf2 = Buffer.from(ab);
// note: a Buffer's underlying buffer may be larger
// (allocUnsafe pools) -> always use byteOffsetSlice, fill, swap
subarray (или slice) возвращает представление, разделяющее исходную память, — изменения видны в обоих. fill записывает байт или повторяющуюся строку по всему буферу. swap16/swap32 меняют порядок байтов на месте для преобразования endianness. Буферы итерируемы и выдают каждое значение байта 0–255.
const buf = Buffer.from('abcdef');
// slice shares memory (no copy) — like subarray
const s = buf.subarray(1, 4); // 'bcd'
s[0] = 88; // mutates buf too -> 'aXcdef'
// fill with a value or pattern
Buffer.alloc(4).fill(0xff); // <Buffer ff ff ff ff>
Buffer.alloc(6).fill('ab'); // 'ababab'
// reverse byte order in place (for endianness swaps)
const n = Buffer.from([0x01, 0x02, 0x03, 0x04]);
n.swap16(); // swaps pairs: <Buffer 02 01 04 03>
// iterate with for...of
for (const byte of buf) console.log(byte); // 97, 98, ...EventEmitter
Создание и генерация событий
EventEmitter — ядро pub/sub в Node. emit(eventName, ...args) испускает событие; on() подписывается. Многие встроенные классы (потоки, HTTP-сервер) наследуют его. Имена событий — произвольные строки, но 'error' особенное. Слушатели вызываются синхронно в порядке регистрации.
const { EventEmitter } = require('events');
class Clock extends EventEmitter {
start() {
this.emit('start', Date.now()); // emit with args
setInterval(() => this.emit('tick', new Date()), 1000);
}
}
const clock = new Clock();
clock.on('tick', date => console.log('tick', date));
clock.on('start', ts => console.log('started at', ts));
clock.start();
// on() == addListener; once() fires only onceonce и removeListener
once() регистрирует слушателя, который автоматически удаляется после срабатывания, — отлично для одноразовой настройки. Чтобы удалить слушателя, нужно сохранить ссылку на ту же функцию (стрелочные функции каждый раз создают новую ссылку). removeAllListeners очищает слушателей одного или всех событий. off — псевдоним removeListener.
const ee = new EventEmitter();
// once: auto-removed after first fire
ee.once('init', () => console.log('init fired'));
// remove a specific listener (need the same function ref)
const handler = () => console.log('hi');
ee.on('msg', handler);
ee.off('msg', handler); // off() == removeListener
// remove all listeners for an event (or all events)
ee.removeAllListeners('msg');
ee.removeAllListeners(); // everything
// inspect
ee.listenerCount('msg');
ee.eventNames(); // ['msg', 'init']События ошибок
Если событие 'error' испущено, а слушателя НЕТ, Node бросает исключение и роняет процесс. Всегда прикрепляйте обработчик ошибок к EventEmitter, особенно к потокам и HTTP-серверам. captureRejections (Node 12+) направляет отклонённые промисы асинхронных слушателей в событие 'error'.
const ee = new EventEmitter();
// 'error' is special: if unhandled, it CRASHES the process
ee.on('error', err => {
console.error('caught:', err.message);
});
// later, emit an error safely
ee.emit('error', new Error('something broke'));
// guard against crashes from unhandled errors
// (monitor with the static capture)
EventEmitter.captureRejections = true; // for async handlers
// always register an error listener on streams/httpАсинхронные слушатели
EventEmitter вызывает слушателей синхронно, поэтому промис асинхронного слушателя не ожидается: emit() возвращается раньше, чем он завершится. Используйте once(ee, name), чтобы дождаться одного события как промиса. Включите captureRejections, чтобы отклонённый асинхронный слушатель вызывал событие 'error', а не терялся молча.
const ee = new EventEmitter();
// listeners run synchronously; await doesn't pause the chain
ee.on('save', async () => {
await fs.promises.writeFile('x', 'y');
console.log('saved');
});
ee.emit('save'); // returns before the await finishes
// wait for async listeners in sequence
const { once } = require('events');
async function waitForReady() {
await once(ee, 'ready'); // promise resolves on first 'ready'
console.log('now ready');
}
// handle async errors properly
EventEmitter.captureRejections = true;
ee.on('job', async () => { throw new Error('boom'); });
ee.on('error', err => console.error(err));Именование событий и newListener
newListener и removeListener — специальные события, испускаемые при добавлении или удалении слушателей, полезны для хуков и профилирования. setMaxListeners повышает порог обнаружения утечек (по умолчанию 10); предупреждение обычно означает, что вы забыли очистить слушателей. Используйте Symbol или константы для имён событий, чтобы избежать опечаток.
const ee = new EventEmitter();
// special events fired by EventEmitter itself
ee.on('newListener', (event, listener) => {
console.log('listener added for', event);
});
ee.on('removeListener', (event, listener) => {
console.log('listener removed for', event);
});
// limit listener count to catch leaks
ee.setMaxListeners(20);
ee.getMaxListeners(); // 20
// MaxListenersExceededWarning fires if exceeded
// convention: camelCase event names, 'error' reserved
// prefer symbols/const strings to avoid typos
const READY = Symbol('ready');
ee.emit(READY);Дочерние процессы
exec (через shell, с буферизацией)
exec() запускает команду через shell и буферизует stdout/stderr — лучше для коротких команд, когда нужен весь вывод сразу. Он порождает shell, поэтому раскр ывает glob-шаблоны и конвейеры. НИКОГДА не подставляйте пользовательский ввод в строку команды — это уязвимость внедрения команд; используйте spawn с массивом аргументов.
const { exec } = require('child_process');
// runs a command in a shell, buffers all output
exec('ls -la', (err, stdout, stderr) => {
if (err) { console.error('failed:', err); return; }
console.log(stdout); // full stdout as a string
console.error(stderr);
});
// promisified (Node 12+)
const { promisify } = require('util');
const execP = promisify(exec);
const { stdout } = await execP('git rev-parse HEAD');
// WARNING: shell interpolation = injection risk!
// NEVER: exec(`rm ${userInput}`)spawn (потоково, без shell)
spawn() запускает процесс с массивом аргументов (без shell) и передаёт stdout/stderr потоком — безопасно и экономно по памяти для больших или долгих выводов. Поскольку аргументы передаются напрямую, без shell, нет раскрытия glob и риска внедрения. Направляйте дочерние потоки в другие потоки для конвейеров.
const { spawn } = require('child_process');
// no shell by default -> safe, stream-based
const child = spawn('ls', ['-la', '/tmp']);
child.stdout.on('data', chunk => process.stdout.write(chunk));
child.stderr.on('data', chunk => process.stderr.write(chunk));
child.on('close', code => console.log('exit code', code));
child.on('error', err => console.error('failed to spawn', err));
// pipe streams directly
const gzip = spawn('gzip');
process.stdin.pipe(gzip.stdin);
gzip.stdout.pipe(process.stdout);execFile и fork
execFile запускает исполняемый файл без shell — безопаснее exec для запуска известного бинарника с аргументами. fork() порождает процесс Node и открывает встроенный IPC-канал (send/on('message')) — основа обмена сообщениями между процессами Node, как в cluster и worker_threads.
const { execFile, fork } = require('child_process');
// execFile: like exec but no shell (safer, slight overhead saving)
execFile('node', ['--version'], (err, stdout) => {
console.log(stdout.trim()); // v20.x.x
});
// fork: spawn another Node process with an IPC channel
const worker = fork('./worker.js');
worker.send({ task: 'compute', n: 100 });
worker.on('message', msg => console.log('result:', msg));
worker.on('exit', code => console.log('worker exited', code));
// in worker.js:
// process.on('message', msg => { process.send(result); });stdio и аргументы
stdio управляет стандартными потоками дочернего процесса: 'inherit' делит терминал родителя (отлично для npm-скриптов), 'ignore' отбрасывает, 'pipe' захватывает. detached + unref() порождает фоновый процесс, переживающий родителя. Передавайте аргументы массивом: spawn сам их экранирует, поэтому пробелы и спецсимволы безопасны.
const { spawn } = require('child_process');
// control stdio: 'pipe' (default), 'inherit', 'ignore', or fd
const child = spawn('npm', ['test'], {
stdio: 'inherit' // child uses parent's stdin/stdout/stderr
});
// per-stream: [stdin, stdout, stderr]
spawn('cat', [], { stdio: ['pipe', process.stdout, 'ignore'] });
// set env, cwd, and detached background process
const bg = spawn('node', ['server.js'], {
cwd: '/app',
env: { ...process.env, NODE_ENV: 'production' },
detached: true // runs independently of parent
});
bg.unref(); // let parent exit without waiting
// pass arguments safely as array (no shell parsing)
spawn('echo', ['hello world']); // one arg, no quotes neededКоды выхода и сигналы
Событие 'exit' сообщает code (null, если процесс убит сигналом) и signal (null при нормальном выходе). 'close' срабатывает после закрытия всех stdio-потоков — используйте его, когда перенаправляли вывод и нужно знать, что потоки сброшены. kill() посылает сигнал; SIGTERM даёт корректное завершение, SIGKILL перехватить нельзя.
const child = spawn('sleep', ['60']);
// 'exit' fires with code + signal
child.on('exit', (code, signal) => {
if (code === 0) console.log('success');
else if (signal) console.log('killed by', signal);
else console.log('failed with code', code);
});
// send a signal to the child (SIGTERM by default)
setTimeout(() => child.kill('SIGTERM'), 1000);
child.kill(); // default SIGTERM
child.kill('SIGKILL'); // force-kill (cannot be caught)
// 'close' vs 'exit': 'close' fires after streams are closed
child.on('close', code => console.log('streams closed', code));
// check if process is still running
child.killed; // true after kill() calledCluster
Базовый кластеринг
cluster позволяет породить несколько процессов Node, разделяющих один порт, и масштабироваться по ядрам CPU. Primary порождает воркеров (обычно os.cpus().length). Каждый воркер — полноценный процесс Node, выполняющий тот же скрипт. Перезапускайте воркеров на событие 'exit' для устойчивости. Используйте cluster.isPrimary (ранее isMaster) для ветвления логики.
const cluster = require('cluster');
const http = require('http');
const os = require('os');
if (cluster.isPrimary) { // old: isMaster
// fork one worker per CPU core
for (let i = 0; i < os.cpus().length; i++) cluster.fork();
cluster.on('exit', (worker, code) => {
console.log(`worker ${worker.process.pid} died`);
cluster.fork(); // restart it
});
} else {
// workers share the same port
http.createServer((req, res) => res.end('hi'))
.listen(3000);
console.log('worker started', process.pid);
}Управление воркерами
Primary отслеживает воркеров через события 'online' (процесс запущен), 'listening' (сервер привязан), 'disconnect' и 'exit'. disconnect() сливает соединения перед уничтожением воркера — и спользуйте для перезагрузки без простоя. cluster.workers отображает ID воркеров на объекты Worker, чтобы отправлять сообщения или закрывать их.
cluster.on('online', worker => {
console.log('worker responsive', worker.id);
});
cluster.on('listening', (worker, address) => {
console.log('worker bound to', address.port);
});
cluster.on('disconnect', worker => {
console.log('worker disconnected', worker.id);
});
// gracefully shut down a worker
const w = cluster.workers[1];
w.disconnect(); // stop accepting connections, then exit
w.send('shutdown'); // custom message
// iterate all workers
for (const id in cluster.workers) {
cluster.workers[id].send({ cmd: 'reload' });
}Общий порт сервера
Все воркеры слушают один порт; primary балансирует входящие соединения. SCHED_RR (round-robin, по умолчанию на большинстве платформ) распределяет равномерно; SCHED_NONE оставляет это ОС. Состояние НЕ разделяется между воркерами — используйте Redis или базу данных для общих сессий и кеша.
const cluster = require('cluster');
const http = require('http');
if (cluster.isPrimary) {
cluster.schedulingPolicy = cluster.SCHED_RR; // round-robin (default on non-Windows)
cluster.fork();
cluster.fork();
} else {
// all workers call listen(3000) — primary load-balances
http.createServer((req, res) => {
res.end(`handled by ${process.pid}`);
}).listen(3000);
}
// SCHED_RR: primary distributes connections (default)
// SCHED_NONE: OS balances (may be uneven)Жизненный цикл и IPC
cluster.fork() открывает IPC-канал (как child_process.fork): worker.send и process.on('message') обмениваются JSON между primary и воркерами. Используйте это для раздачи задач или сигнала корректного завершения. Для тяжёлых вычислений рассмотрите также worker_threads: они разделяют память и и збегают накладных расходов IPC.
// primary -> worker messaging
if (cluster.isPrimary) {
const worker = cluster.fork();
worker.on('message', msg => console.log('from worker:', msg));
worker.send({ task: 'heavy-compute' });
} else {
process.on('message', msg => {
console.log('from primary:', msg);
// do work, then report back
process.send({ done: true, result: 42 });
});
}
// graceful shutdown signal
process.on('message', msg => {
if (msg === 'shutdown') {
server.close(() => process.exit(0));
}
});Плавная перезагрузка (без простоя)
Rolling restart перезагружает воркеров по одному, чтобы приложение не падало: отключите воркер (он перестаёт принимать новые соединения), дождитесь его выхода после слива соединений, затем породите замену. Запускайте по SIGHUP. Всегда сочетайте с сообщением 'shutdown' для каждого воркера, чтобы он закрывал сервер и выходил только после завершения текущих запросов.
// rolling restart: reload workers one at a time
function reload() {
const workers = Object.values(cluster.workers || {});
let i = 0;
const next = () => {
if (i >= workers.length) return;
const w = workers[i++];
w.send('shutdown'); // tell worker to drain
w.disconnect(); // stop accepting connections
w.once('exit', () => {
cluster.fork(); // replacement ready
next(); // move to the next
});
};
next();
}
// trigger reload on SIGHUP
process.on('SIGHUP', reload);
// in the worker: finish in-flight requests then exit
process.on('message', msg => {
if (msg === 'shutdown') server.close(() => process.exit(0));
});Асинхронное программирование
Callback и соглашение error-first
Классический асинхронный паттерн Node — callback с ошибкой первым аргументом: первый аргумент ошибка (null при успехе), последующие — результаты. Всегда проверяйте err первым и выходите раньше при сбое. Этот стиль плохо масштабируется при вложенности (callback hell), поэтому современный код использует промисы и async/await.
// Node callbacks: (err, result) => {}
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) return console.error('read failed', err);
console.log(data);
});
// custom error-first function
function divide(a, b, cb) {
if (b === 0) return cb(new Error('divide by zero'));
cb(null, a / b);
}
divide(10, 2, (err, result) => {
if (err) return console.error(err);
console.log(result); // 5
});Промисы
Promise представляет будущее значение. then() обрабатывает успех, catch() — отказ, finally() выполняется в обоих случаях. Сцепляйте then() для последовательного преобразования значений. util.promisify превращает функцию с error-first callback в возвращающую Promise — мост от устаревших API к async/await.
// create a promise
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('done'), 100);
});
// consume with then/catch/finally
p.then(val => console.log(val)) // 'done'
.catch(err => console.error(err))
.finally(() => console.log('settled'));
// chain transforms
fetch(url)
.then(r => r.json())
.then(data => render(data));
// convert callback APIs
const { promisify } = require('util');
const readFile = promisify(fs.readFile);
const text = await readFile('x.txt', 'utf8');async/await
async/await делает асинхронный код похожим на синхронный. Асинхронная функция возвращает Promise; await приостанавливает выполнение до его завершения. Оборачивайте awaited-вызовы в try/catch для обработки отказов. Top-level await разрешён в ES-модулях (и с флагом в CommonJS), избавляя от обёртки в виде async IIFE.
// async functions always return a Promise
async function loadUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error('not found');
return res.json();
}
// consume with try/catch
try {
const user = await loadUser(5);
console.log(user);
} catch (err) {
console.error('failed:', err);
}
// top-level await works in ESM and CommonJS (Node 14.8+)
const config = await loadConfig();Promise.all и allSettled
Promise.all запускает промисы параллельно и разрешается массивом результатов, но отклоняется сразу, если ЛЮБОЙ промис отклонён (fast-fail) — используйте, когда все должны завершиться успешно. Promise.allSettled ждёт каждый промис независимо от исхода, возвращая объекты {status, value/reason}, — лучший выбор, когда допустим частичный успех.
// all: run in parallel, reject fast on first failure
const [a, b, c] = await Promise.all([
fetch('/a').then(r => r.json()),
fetch('/b').then(r => r.json()),
fetch('/c').then(r => r.json())
]);
// allSettled: wait for ALL, never rejects
const results = await Promise.allSettled([
fetch('/x'),
fetch('/y'),
fetch('/z')
]);
results.forEach(r => {
if (r.status === 'fulfilled') console.log(r.value);
else console.error(r.reason); // rejected reason
});Promise.race и Promise.any
Promise.race разрешается ИЛИ отклоняется с первым завершившимся промисом — полезно для таймаутов и гонки зеркал. Promise.any разрешается первым успехом и отклоняется (AggregateError), только если все промисы провалились, — идеально для резервных эндпоинтов, где достаточно одного здорового ответа.
// race: first to SETTLE (resolve or reject) wins
const fastest = await Promise.race([
fetch('/primary'),
fetch('/mirror'),
timeout(5000)
]);
// any: first to FULFILL wins; rejects only if ALL reject
const alive = await Promise.any([
fetch('/node1'),
fetch('/node2'),
fetch('/node3')
]);
// implement a timeout with race
function withTimeout(p, ms) {
return Promise.race([
p,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('timeout')), ms))
]);
}Последовательно против параллельно
Await в цикле выполняется последовательно (медленно). Сопоставьте массив промисов и передайте их в Promise.all для параллельности (быстро, но неограниченная конкурентность может перегрузить ресурсы). Пул с ограничением конкурентности дросселирует параллельную работу — необходим при вызове API с rate limit или тяжёлом I/O по тысячам элементов.
// SEQUENTIAL: one after another (slow)
const results = [];
for (const url of urls) {
results.push(await fetch(url).then(r => r.json()));
}
// PARALLEL: fire all, await together (fast)
const results = await Promise.all(
urls.map(u => fetch(u).then(r => r.json()))
);
// THROTTLED: limit concurrency with a pool
async function mapLimit(items, limit, fn) {
const ret = [];
const executing = [];
for (const item of items) {
const p = Promise.resolve().then(() => fn(item));
ret.push(p);
if (executing.push(p) >= limit) {
await Promise.race(executing);
executing.splice(executing.findIndex(x => x === p), 1);
}
}
return Promise.all(ret);
}Обработка ошибок
try/catch/finally
try/catch обрабатывает синхронные ошибки и (с await) асинхронные отказы. finally выполняется всегда, даже при return/throw, — используйте для очистки вроде закрытия дескрипторов. Перехватывайте конкретные ошибки по err.code и пробрасывайте незнакомые, чтобы неожиданные баги всплывали, а не проглатывались.
function parse(str) {
try {
return JSON.parse(str);
} catch (err) {
console.error('parse failed:', err.message);
return null;
} finally {
console.log('cleanup always runs');
}
}
// async errors need async catch
async function load() {
try {
const data = await fetchData();
return data;
} catch (err) {
if (err.code === 'ENOENT') return defaultData();
throw err; // re-throw unknown errors
}
}Error-first callbacks
В callback с ошибкой первым аргументом всегда проверяйте err первым и выходите раньше — никогда не используйте данные, когда err установлен. Оборачивая callback-API, передавайте ошибку в свой callback, а не бросайте её (броски внутри callback не поймает вызывающий). Оборачивайте в try/catch синхронный код, который может бросить (н апример, JSON.parse).
const fs = require('fs');
// ALWAYS check err first, return early
fs.readFile('missing.txt', 'utf8', (err, data) => {
if (err) {
console.error('could not read:', err.message);
return; // don't use data
}
console.log(data);
});
// propagate the error to your own caller
function readConfig(cb) {
fs.readFile('config.json', 'utf8', (err, raw) => {
if (err) return cb(err);
try { cb(null, JSON.parse(raw)); }
catch (e) { cb(e); }
});
}Необработанные исключения
uncaughtException срабатывает на синхронные исключения, ускользнувшие от всех обработчиков, — процесс уже повреждён; залогируйте, закройте сервер и выйдите (пусть менеджер процессов перезапустит вас). unhandledRejection срабатывает на забытые промисы; с Node 15 они роняют процесс, поэтому всегда добавляйте .catch() или await в try/catch.
// last-resort handler for sync exceptions
process.on('uncaughtException', err => {
console.error('UNCAUGHT:', err);
// the process is in an unknown state — restart it
server.close(() => process.exit(1));
});
// rejected promises nobody awaited
process.on('unhandledRejection', (reason, promise) => {
console.error('UNHANDLED REJECTION:', reason);
});
// Node 15+: unhandled rejections terminate the process
// always add .catch() or wrap in try/awaitСобственные классы ошибок
Наследуйтесь от Error, чтобы добавить структурированные поля (code, field, status) и различать типы ошибок через instanceof. Всегда задавайте this.name равным имени класса (в старых целях это не автоматически) и вызывайте super(message). Собственные ошибки делают catch читаемым: ветвление по instanceof вместо хрупкого сравнения строк.
// subclass Error to add context
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
this.code = 'VALIDATION_FAILED';
}
}
function validate(email) {
if (!email.includes('@')) {
throw new ValidationError('email', 'invalid email');
}
}
// branch on error type with instanceof
try {
validate('no-at-sign');
} catch (err) {
if (err instanceof ValidationError) {
console.log(err.field, err.message);
} else {
throw err;
}
}Свойства ошибок и cause
У каждой Error есть message, name и stack. Добавьте свойство code для стабильной машинно-читаемой обработки (собственные ошибки Node используют коды вроде ENOENT, EACCES). Опция cause из ES2022 (Node 16.9+) сцепляет нижележащую ошибку, позволяя оборачивать низкоуровневые сбои, сохраняя исходный стек для отладки.
// built-in Error props
const e = new Error('something broke');
e.message; // 'something broke'
e.stack; // stack trace string
e.name; // 'Error'
// add a code for machine-readable handling
const err = new Error('file missing');
err.code = 'ENOENT';
err.errno = -2;
// Error.cause (Node 16.9+) — chain underlying errors
try {
JSON.parse(bad);
} catch (original) {
throw new Error('config parse failed', { cause: original });
}
// inspect the cause
console.log(err.cause); // the original SyntaxErrorDomains и очистка
Используйте 'beforeExit' для асинхронной очистки (он может отложить выход), а 'exit' — только для синхронной работы. Обрабатывайте SIGTERM (остановка контейнера) и SIGINT (Ctrl-C), чтобы слить соединения перед выходом, и добавьте таймаут принудительного выхода, чтобы зависшее соединение не подвесило процесс. Domains устарели; используйте try/catch и асинхронную обработку ошибок.
// modern cleanup: 'beforeExit' for async, 'exit' for sync
process.on('beforeExit', async () => {
await closeDbConnections();
});
process.on('exit', code => {
// ONLY sync code allowed here — no async, no promises
console.log('exiting with', code);
});
// graceful signal handling
const shutdown = sig => {
console.log('got', sig);
server.close(() => process.exit(0));
setTimeout(() => process.exit(1), 5000).unref(); // force exit
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));Отладка
Методы console
console умеет больше, чем log: table рисует массивы объектов, time/timeEnd измеряет длительность, dir выводит объект с настраиваемой глубиной, trace печатает стек, count подсчитывает попадания. Используйте console.error (stderr), чтобы в продакшен-конвейерах можно было разделить логи и ошибки.
console.log('basic'); // stdout
console.error('oops'); // stderr
console.warn('careful'); // stderr
// formatted table
console.table([{ id: 1, n: 'A' }, { id: 2, n: 'B' }]);
// inspect an object in depth
console.dir(obj, { depth: null, colors: true });
// timing a block
console.time('loop');
for (let i = 0; i < 1e6; i++) {}
console.timeEnd('loop'); // loop: 3.2ms
// stack trace
console.trace('where am I');
// count calls
for (let i = 0; i < 3; i++) console.count('hit');node inspect и DevTools
--inspect запускает инспектор V8, к которому подключаются Chrome DevTools (chrome://inspect) или VS Code. --inspect-brk останавливается на первой строке, чтобы можно было поставить точки останова до выполнения кода запуска. Классический 'node inspect' — терминальный отладчик, полезный по SSH, где нет браузера.
# open Chrome DevTools debugger
node --inspect app.js
# visit chrome://inspect, click "inspect"
# pause on first line (break before anything runs)
node --inspect-brk app.js
# wait for a debugger client to attach
node --inspect-wait app.js
# the legacy CLI debugger (still works, no browser)
node inspect app.js
# > cont, step, next, breakpoints, replОператор debugger
Оператор debugger приостанавливает выполнение ТОЛЬКО когда подключён отладчик (DevTools или VS Code), иначе это пустая операция, безопасная для оставления в коде. Сочетайте с --inspect-brk, чтобы остановиться при запуске. Для точечного осмотра вставляйте debugger; в циклы или условия вместо установки точек в UI.
function findBug(arr) {
let sum = 0;
for (const n of arr) {
debugger; // pauses only when a debugger is attached
sum += n;
}
return sum;
}
// run with --inspect-brk to hit the breakpoint
// node --inspect-brk app.js
// conditional breakpoints in DevTools/VSCode:
// if (n > 100) { debugger; }Отладка в VS Code
Отладчик Node в VS Code (F5) читает .vscode/launch.json. "request": "launch" запускает программу со встроенным инспектором; "attach" подключается к процессу, уже запущенному с --inspect. skipFiles скрывает внутренности Node от пошагового выполнения. Используйте флаг "restart" или nodemon для авто-перезапуска при изменениях файлов.
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug App",
"program": "${workspaceFolder}/app.js",
"skipFiles": ["<node_internals>/**"]
},
{
"type": "node",
"request": "attach",
"name": "Attach by PID",
"processId": "${command:PickProcess}"
}
]
}
// F5 to start; set breakpoints in the editor
// "restart": true, "nodemon" for auto-restart on changeПредупреждения и стеки
--trace-warnings печатает стеки для предупреждений процесса (утечки памяти, устаревшие API). --trace-deprecation выявляет использование legacy-API; --throw-deprecation превращает их в жёсткие ошибки для строгого CI. --cpu-prof пишет профиль, который можно открыть в Chrome DevTools и найти горячие функции. Увеличьте Error.stackTraceLimit для более глубоких асинхронных стеков.
# show stack traces for process warnings
node --trace-warnings app.js
# deprecation warnings (use --throw-deprecation to make them errors)
node --trace-deprecation app.js
# capture a stack trace manually
const e = new Error('here');
console.log(e.stack);
# show async stack traces (Node 12+ enabled by default)
Error.stackTraceLimit = 50; // deeper traces
# profile CPU usage
node --cpu-prof app.js # writes CPU.*.cpuprofile
# then load the file in Chrome DevToolsКриптография
Хеширование (createHash)
createHash создаёт односторонний дайджест. SHA-256 — современный стандарт для контрольных сумм и подписей; избегайте MD5/SHA-1 для безопасности (подвержены коллизиям). Данные можно подавать инкрементально и передавать большие файлы потоком без буферизации. digest('hex') возвращает hex-строку; 'base64' тоже распространён. Хеширование — НЕ хранение паролей: используйте pbkdf2/scrypt.
const crypto = require('crypto');
// common hashes: sha256, sha512, md5 (insecure!), sha1
const hash = crypto.createHash('sha256');
hash.update('hello');
hash.update(' world'); // can chain updates
console.log(hash.digest('hex'));
// b94d... (64 hex chars)
// one-shot hashing
const h = crypto.createHash('sha256').update('data').digest('hex');
console.log(h);
// file hash (streaming)
const fs = require('fs');
const fhash = crypto.createHash('sha256');
fs.createReadStream('big.iso').on('data', c => fhash.update(c))
.on('end', () => console.log(fhash.digest('hex')));HMAC (createHmac)
HMAC подписывает данные общим секретом, чтобы получатель мог проверить и целостность, и подлинность. Это основа подписей JWT и проверки вебхуков (GitHub, Stripe). Всегда сравнивайте подписи через timingSafeEqual: обычный === утекает информацию через разницу во времени, которую атакующие могут использовать.
const crypto = require('crypto');
// HMAC = keyed hash (authenticity + integrity)
const secret = process.env.SECRET_KEY;
const hmac = crypto.createHmac('sha256', secret);
hmac.update('payload to sign');
const signature = hmac.digest('hex');
// verify a webhook signature (constant-time compare)
function verify(payload, receivedSig) {
const expected = crypto.createHmac('sha256', secret)
.update(payload).digest('hex');
// timingSafeEqual prevents timing attacks
return crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(receivedSig)
);
}Случайные байты
crypto.randomBytes даёт криптографически стойкие случайные данные — используйте для токенов, ID и секретов. Асинхронная форма не блокирует цикл событий при генерации множества байтов. crypto.randomInt даёт несмещённые случайные целые, а randomUUID() генерирует UUID v4 по RFC-4122. Никогда не используйте Math.random() для чего-либо, связанного с безопасностью.
const crypto = require('crypto');
// async (preferred — doesn't block the event loop)
crypto.randomBytes(16, (err, buf) => {
const token = buf.toString('hex'); // 32-char hex
});
// sync (blocks; fine for small sizes)
const id = crypto.randomBytes(8).toString('hex');
// random integer in [min, max)
const n = crypto.randomInt(1, 101); // 1..100
// random UUID (Node 14.17+)
const uuid = crypto.randomUUID();
// '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
// use crypto, NEVER Math.random() for secrets!Шифрование (createCipheriv)
AES-256-GCM — рекомендуемый симметричный шифр: он аутентифицированный, поэтому подмена обнаруживается. IV (nonce) должен быть уникальным для каждого шифрования с данным ключом (никогда не переиспользуйте); храните его вместе с шифротекстом. setAuthTag проверяет целостность при расшифровке. Никогда не используйте устаревший createCipher (он небезопасно выводит ключи) — всегда createCipheriv с правильным ключом.
const crypto = require('crypto');
const algorithm = 'aes-256-gcm';
// AES-256-GCM (authenticated encryption) ----------------
const key = crypto.randomBytes(32); // 256-bit key
const iv = crypto.randomBytes(12); // 96-bit nonce
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
const enc = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag(); // GCM auth tag
return { enc, tag };
}
function decrypt(enc, tag) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
decipher.setAuthTag(tag); // verify integrity
return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
}Хеширование паролей (pbkdf2, scrypt)
Хешируйте пароли медленной KDF с солью — никогда обычным хешем. pbkdf2 (увеличивайте число итераций по мере роста аппаратных мощностей) и scrypt (memory-hard, устойчив к GPU) встроены в Node. Храните итерации, соль и хеш вместе, чтобы проверять и позже повышать параметры. Используйте timingSafeEqual для проверки хешей без утечки информации о времени.
const crypto = require('crypto');
// PBKDF2: tuned with iterations
function hashPbkdf2(password) {
const salt = crypto.randomBytes(16);
const iterations = 100000;
const hash = crypto.pbkdf2Sync(password, salt, iterations, 64, 'sha256');
return `${iterations}.${salt.toString('hex')}.${hash.toString('hex')}`;
}
// scrypt: memory-hard, resistant to GPU/ASIC attacks
function hashScrypt(password) {
const salt = crypto.randomBytes(16);
const hash = crypto.scryptSync(password, salt, 64, { N: 16384 });
return salt.toString('hex') + '.' + hash.toString('hex');
}
// verify: re-hash with the same salt and compare
function verify(password, stored) {
const [iter, salt, hash] = stored.split('.');
const computed = crypto.pbkdf2Sync(password, Buffer.from(salt, 'hex'),
+iter, 64, 'sha256');
return crypto.timingSafeEqual(Buffer.from(hash, 'hex'), computed);
}Сравнение за постоянное время
timingSafeEqual сравнивает два буфера за постоянное время, предотвращая timing-атаки, где злоумышленник выводит секрет побайтово по задержкам ответа. Оба буфера должны быть одинаковой длины (проверьте заранее, но сама эта проверка может выдать длину — для секретов сначала хешируйте обе стороны). Используйте при сравнении токенов, подписей и API-ключей.
const crypto = require('crypto');
// NORMAL compare leaks via timing (returns early on first diff)
// 'secret' === userInput // BAD for secrets
// timingSafeEqual takes equal-length Buffers
function safeEqual(a, b) {
const bufA = Buffer.from(a);
const bufB = Buffer.from(b);
if (bufA.length !== bufB.length) return false;
return crypto.timingSafeEqual(bufA, bufB);
}
// common use: API key check
function auth(req) {
const provided = req.headers['x-api-key'] || '';
return safeEqual(provided, process.env.API_KEY);
}Модуль OS
Информация о системе
os даёт доступ к окружению хоста. platform/arch/type идентифицируют ОС для проверок переносимости. os.EOL даёт последовательность конца строки платформы — используйте её при создании текстовы х файлов с правильными переводами строк. hostname — сетевое имя машины, полезно для логирования того, какой экземпляр обработал запрос.
const os = require('os');
os.platform(); // 'linux', 'darwin', 'win32'
os.arch(); // 'x64', 'arm64'
os.type(); // 'Linux', 'Darwin', 'Windows_NT'
os.release(); // kernel version
os.hostname(); // machine hostname
os.uptime(); // seconds since boot
os.EOL; // '\n' (POSIX) or '\r\n' (Windows)
// detect platform portably
const isWin = os.platform() === 'win32';
const isMac = os.platform() === 'darwin';Информация о CPU
os.cpus() возвращает массив логических ядер (включая гипертреды), поэтому его длина — правильная подсказка конкурентности для cluster.fork. Каждая запись имеет model, speed и times (user/sys/idle). loadavg сообщает системную нагрузку (только Linux/macOS): значение выше cpus().length говорит о насыщении.
const os = require('os');
// logical core count (threads, not physical)
os.cpus().length; // 8
// detailed per-core info
os.cpus().forEach((cpu, i) => {
console.log(`core ${i}: ${cpu.model} @ ${cpu.speed}MHz`);
});
// 1/5/15-minute load averages (NOT on Windows)
os.loadavg(); // [0.45, 0.32, 0.28]
// set process scheduling priority
os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);Память
os.totalmem/freemem сообщают RAM системы, а process.memoryUsage — потребление этого процесса. rss — память на уровне ОС; heapUsed — живые JS-объекты. Следите за heapUsed на предмет утечек. Чтобы перевести байты в МБ, делите на 1024*1024 (1048576). Настраивайте --max-old-space-size, когда куча приближается к лимиту.
const os = require('os');
// system memory (bytes)
os.totalmem(); // e.g. 17179869184
os.freemem(); // currently free bytes
// process memory usage (bytes)
const m = process.memoryUsage();
m.rss; // resident set size (total RAM held)
m.heapTotal; // V8 heap allocated
m.heapUsed; // V8 heap actually used
m.external; // C++ objects bound to JS
m.arrayBuffers; // memory in ArrayBuffers
// human-readable
console.log(`heap: ${(m.heapUsed / 1048576).toFixed(1)} MB`);Сетевые интерфейсы
os.networkInterfaces() перечисляет каждый сетевой интерфейс с адресами, MAC и семейством (IPv4/IPv6). Флаг 'internal' отмечает loopback. Это переносимый способ узнать LAN-IP машины для привязки серверов или логирования. У каждого интерфейса может быть несколько адресов (многосетевые хосты).
const os = require('os');
const nets = os.networkInterfaces();
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
console.log(`${name} ${net.family}: ${net.address} (${net.mac})`);
}
}
// en0 IPv4: 192.168.1.10 (aa:bb:cc:...)
// lo IPv4: 127.0.0.1 (:::...)
// find this machine's LAN IPv4
function getLanIp() {
for (const nets of Object.values(os.networkInterfaces())) {
for (const n of nets) {
if (n.family === 'IPv4' && !n.internal) return n.address;
}
}
return '127.0.0.1';
}Пользователь и пути
os.homedir возвращает домашний каталог пользователя, os.tmpdir — системную временную папку; оба учитывают платформу, поэтому предпочитайте их жёстко заданным путям. os.userInfo даёт идентичность текущего пользователя. os.constants централизует числовые значения сигналов, errno и приоритетов, чтобы не жёстко кодировать магические числа вроде 15 для SIGTERM.
const os = require('os');
os.homedir(); // /home/alice or C:\Users\alice
os.tmpdir(); // /tmp or C:\Users\...\Temp
os.userInfo(); // { username, uid, gid, homedir, shell }
os.constants; // signal/errno/priority constants
// errno constants map
os.constants.errno.ENOENT; // -2
// signal constants
os.constants.signals.SIGTERM; // 15
// priority constants
os.constants.priority.PRIORITY_HIGH;
// build a portable temp path
const path = require('path');
const tmpFile = path.join(os.tmpdir(), 'app-' + Date.now() + '.log');Process
process.argv
process.argv хранит аргументы командной строки: argv[0] — бинарник node, argv[1] — скрипт, остальные — пользовательские аргументы. Отрежьте первые два, чтобы получить только пользовательские. Для чего-то серьёзнее игрушечных скриптов используйте парсер вроде minimist, yargs или commander: они обрабатывают флаги, типы, значения по умолчанию и справку.
// argv[0] = node path, argv[1] = script path, argv[2+] = args
// node app.js --port 3000 users.csv
console.log(process.argv);
// ['/usr/bin/node', '/app/app.js', '--port', '3000', 'users.csv']
const args = process.argv.slice(2);
console.log(args); // ['--port', '3000', 'users.csv']
// minimal flag parsing
function parseArgs(arr) {
const out = { _: [] };
for (let i = 0; i < arr.length; i++) {
if (arr[i].startsWith('--')) out[arr[i].slice(2)] = arr[++i];
else out._.push(arr[i]);
}
return out;
}
// for real CLI use commander, yargs, or minimistprocess.env
process.env хранит переменные окружения как строки. Обычно PORT, NODE_ENV, DATABASE_URL и API_KEY берутся из окружения, чтобы один и тот же код работал в разных средах. Используйте пакет dotenv для загрузки .env-файла при разработке. Никогда не коммитьте секреты — передавайте их через окружение хоста/CI.
// read environment variables
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const nodeEnv = process.env.NODE_ENV || 'development';
const isProd = process.env.NODE_ENV === 'production';
// set an env var (affects child processes too)
process.env.MY_VAR = 'value';
// load .env files (install: npm i dotenv)
// require('dotenv').config();
// enumerate everything
for (const [k, v] of Object.entries(process.env)) {
console.log(k, '=', v);
}process.exit и коды выхода
process.exit(n) завершает процесс немедленно, возможно, до сброса буферов ввода-вывода; предпочитайте устанавливать process.exitCode и давать циклу событий опустеть естественно. Код 0 означает успех; ненулевой сигнализирует об ошибке оболочкам и CI. Соглашение 128+N кодирует завершение сигналом N (поэтому SIGTERM даёт 143).
// exit immediately with a status code
process.exit(0); // success
process.exit(1); // general failure
// exit code is also settable
process.exitCode = 2; // used if the loop ends naturally
// prefer setting exitCode + returning over process.exit()
// so async work can finish
// common conventions:
// 0 success
// 1 general error
// 2 misuse (bad args)
// 124 timeout (from the 'timeout' command)
// 128+N killed by signal N (e.g. 143 = SIGTERM)stdin / stdout / stderr
process.stdout и process.stderr — writable-потоки: write() не добавляет перевод строки (в отличие от console.log). stdin — readable-поток, который можно потреблять через события 'data' или асинхронную итерацию (самый чистый современный паттерн). Используйте stderr для диагностики, чтобы её можно было отделить от реального вывода в конвейерах.
// stdout/stderr are writable streams
process.stdout.write('no newline');
process.stdout.write('line\n');
console.log === process.stdout.write.bind(...); // roughly
// stdin is a readable stream
process.stdin.setEncoding('utf8');
process.stdin.on('data', chunk => console.log('got:', chunk));
// read all of stdin (async iteration)
async function readStdin() {
let data = '';
for await (const chunk of process.stdin) data += chunk;
return data;
}
// ask a yes/no question
process.stdin.resume();
process.stdin.once('data', input => process.exit(input[0] === 'y'.charCodeAt(0) ? 0 : 1));События процесса (сигналы)
'exit' срабатывает после опустошения цикла событий — там выполняется только синхронный код. 'beforeExit' может выполнять асинхронную работу и откладывать выход. Обрабатывайте SIGINT (Ctrl-C) и SIGTERM (docker stop, kill), чтобы корректно закрывать серверы и соединения с БД. Всегда ставьте таймаут принудительного выхода, чтобы зависшее соединение не удерживало процесс навсегда.
// lifecycle events
process.on('exit', code => {
// sync only here — no async, no event loop
console.log('bye, code', code);
});
process.on('beforeExit', () => {
// async OK; can postpone exit
});
// signal handlers (Unix + Windows for SIGINT/SIGTERM)
process.on('SIGINT', () => { // Ctrl-C
console.log('graceful shutdown...');
server.close(() => process.exit(0));
});
process.on('SIGTERM', () => { // kill / docker stop
server.close(() => process.exit(0));
});
process.on('SIGHUP', () => reloadConfig());memoryUsage и uptime
process открывает идентичность (pid, ppid, platform, version) и статистику работы (uptime, memoryUsage, cpuUsage). cwd() — рабочий каталог; chdir меняет его, влияя на разрешение относительных путей. memoryUsage и cpuUsage — основа эндпоинтов проверки здоровья и метрик автоскейлинга.
// process info
process.pid; // OS process ID
process.ppid; // parent PID
process.platform; // 'linux', 'darwin', 'win32'
process.version; // 'v20.11.0'
process.versions; // { v8, openssl, modules, ... }
process.cwd(); // current working directory
process.uptime(); // seconds since process started
// change directory
process.chdir('/tmp');
// memory snapshot
const m = process.memoryUsage();
console.log(m.rss, m.heapUsed);
// CPU usage of this process
const cpu = process.cpuUsage();
console.log(cpu.user, cpu.system); // microsecondsСеть (net)
TCP-сервер
net.createServer создаёт сырой TCP-сервер. Каждое соединение вызывает callback с Socket (Duplex-потоком). Читайте через события 'data', пишите через socket.write. Всегда обрабатывайте 'error' на сокетах, иначе процесс упадёт. TCP — фундамент под HTTP, полезен для собственных протоколов, игр и прокси.
const net = require('net');
const server = net.createServer(socket => {
console.log('client connected', socket.remoteAddress);
socket.write('welcome\n');
socket.on('data', data => {
socket.write('echo: ' + data); // echo back
});
socket.on('end', () => console.log('client left'));
socket.on('error', err => console.error('socket err', err));
});
server.listen(5000, () => {
console.log('TCP server on port 5000');
});
// test with: nc localhost 5000 or telnet localhost 5000TCP-клиент
net.connect (псевдоним createConnection) открывает клиентский TCP-сокет. Callback срабатывает при подключении; события 'data' доставляют входящие байты. Задайте кодировку, чтобы получать строки вместо Buffer. Как и любой поток, обрабатывайте 'error', чтобы избежать падений. Сокеты автоматически закрываются на 'end'; вызовите client.end(), чтобы полузакрыть свою сторону.
const net = require('net');
// connect to a TCP server
const client = net.connect(5000, 'localhost', () => {
console.log('connected');
client.write('hello server\n');
});
client.setEncoding('utf8');
client.on('data', data => console.log('server said:', data));
client.on('end', () => console.log('disconnected'));
client.on('error', err => console.error(err));
// or with an options object + timeout
const c = net.createConnection({
port: 5000,
host: 'localhost',
timeout: 5000
});События сокета и данные
TCP — поток байтов, а не протокол сообщений: одно событие 'data' не равно одному сообщению; данные могут дробиться или склеиваться. Вы ОБЯЗАНЫ сами размечать сообщения (префиксы длины, разделители или парсер). setKeepAlive обнаруживает мёртвых пиров, setTimeout убивает простаивающие соединения, а 'drain' сигнализирует об опустошении буфера записи.
const net = require('net');
net.createServer(socket => {
socket.setEncoding('utf8');
socket.setKeepAlive(true, 30000); // enable TCP keepalive
socket.setTimeout(60000); // idle timeout
socket.on('data', chunk => {
// TCP is a STREAM: chunks may split or merge messages.
// Frame your protocol (length prefix, delimiter, etc.)
console.log('received', chunk.length, 'bytes');
});
socket.on('timeout', () => socket.end());
socket.on('close', hadError => console.log('closed', hadError));
socket.on('drain', () => console.log('buffer drained'));
}).listen(5000);Запись и полное закрытие
socket.write уважает backpressure (возвращает false при заполнении, ждите 'drain'). end() полузакрывает: сбрасывает ожидающие записи, затем отправляет FIN, продолжая читать пира. destroy() убивает сокет немедленно. Используйте remoteAddress/remotePort для логирования и контроля доступа. Pause/resume притормаживают быстрого отправителя.
const net = require('net');
net.createServer(socket => {
// write() returns false when the buffer is full (backpressure)
const ok = socket.write(bigPayload);
if (!ok) socket.once('drain', writeMore);
// half-close: send FIN, keep reading
socket.end(); // writes any pending data, then closes our side
// socket.end('final message\n'); // write + close
// fully destroy the socket immediately
socket.destroy();
// pause/resume reading
socket.pause();
socket.resume();
// address info
socket.remoteAddress; // '192.168.1.5'
socket.remotePort; // 54321
}).listen(5000);События сервера и IPC
net.Server испускает 'connection' (на каждого клиента), 'listening', 'error' (обрабатывайте EADDRINUSE) и 'close'. listen может принимать путь для Unix-сокета (или именованного канала в Windows) — быстрый и безопасный локальный IPC между процессами на одном хосте. server.close() перестаёт принимать новые соединения и ждёт завершения существующих.
const net = require('net');
const server = net.createServer();
server.on('connection', socket => {}); // same as createServer cb
server.on('listening', () => console.log('bound'));
server.on('error', err => {
if (err.code === 'EADDRINUSE') console.error('port taken');
});
server.on('close', () => console.log('server closed'));
server.listen(5000);
// Unix domain socket / named pipe (fast local IPC)
server.listen('/tmp/app.sock');
// Windows: server.listen('\\\\.\\pipe\\app');
// stop accepting, close idle connections
server.close(() => console.log('all done'));
// get bound address
server.address(); // { port: 5000, family: 'IPv4', address: '::' }Таймеры и утилиты
Таймеры (setTimeout, setInterval)
setTimeout выполняется один раз через задержку, setInterval повторяется. setImmediate выполняется после событий ввода-вывода в том же обороте цикла. queueMicrotask выполняется ещё раньше, сразу после текущей операции. Порядок внутри оборота: сначала микрозадачи, затем таймеры, затем I/O, затем setImmediate — полезно знать при планировании последующей работы.
// run once after a delay (ms)
const t = setTimeout(() => console.log('hi'), 1000);
// run repeatedly every interval
const i = setInterval(() => console.log('tick'), 2000);
// run right after the current event loop turn
setImmediate(() => console.log('immediate'));
// run before the next event loop turn (microtask)
queueMicrotask(() => console.log('microtask'));
// order inside one loop:
// microtasks -> timers -> I/O -> check (setImmediate)Очистка таймеров и ref
У каждого таймера есть парная функция очистки. unref() помечает таймер как «не удерживать процесс живым»: если остались только unref-таймеры, Node выходит (удобно для периодической очистки, которая не должна удерживать процесс). ref() отменяет это. Дополнительные аргументы после задержки передаются в callback, избавляя от лишней стрелочной функции.
const t = setTimeout(() => {}, 1000);
clearTimeout(t); // cancel
const i = setInterval(() => {}, 1000);
clearInterval(i);
const imm = setImmediate(() => {});
clearImmediate(imm);
// keep the event loop alive?
// timers do by default; unref() lets the process exit if
// only this timer is pending
const timer = setInterval(() => {}, 1000);
timer.unref(); // won't keep Node alive
timer.ref(); // keep alive again
// pass args to the callback
setTimeout((a, b) => console.log(a, b), 500, 'x', 'y');util.inspect и format
util.format строит строки с плейсхолдерами в стиле printf (%s %d %j %o %O %%). util.inspect отображает любой объект — передайте { depth: null, colors: true } для полного цветного дампа, полезного в логах. util.deprecate оборачивает функцию, чтобы при вызове выдавать DeprecationWarning (виден с --trace-deprecation).
const util = require('util');
// format like printf
util.format('%s:%d', 'port', 3000); // 'port:3000'
util.format('%j', { a: 1 }); // JSON
// deep inspect an object (what console.dir uses)
util.inspect(obj, { depth: null, colors: true, compact: false });
// pretty-print a function (its source)
util.inspect(function f() { return 1; });
// deprecate an API with a warning
const oldFn = util.deprecate(
() => doThingOldWay(),
'oldFn() is deprecated, use newFn() instead'
);util.promisify
util.promisify оборачивает функцию с error-first callback в возвращающую Promise — мост от legacy callback-API к async/await. Многие основные модули теперь поставляют нативные promise-версии (fs/promises), которые предпочтительнее, но promisify всё ещё спасает сторонние callback-API. Функция может определить [util.promisify.custom], чтобы управлять преобразованием.
const util = require('util');
const fs = require('fs');
// turn an error-first callback fn into a promise fn
const readFile = util.promisify(fs.readFile);
const text = await readFile('data.txt', 'utf8');
// works on custom functions too
function delay(ms, cb) { setTimeout(() => cb(null, ms), ms); }
const delayP = util.promisify(delay);
await delayP(100);
// custom promisify symbol (controls the promise behavior)
// const { promisify } = util;
// obj[util.promisify.custom] = () => Promise.resolve(42);
// many core modules ship promise versions directly:
// require('fs/promises'), require('dns/promises')util types и callbackify
util.types предлагает надёжные проверки типов (isPromise, isAsyncFunction, isRegExp, isMap), которые лучше instanceof переживают кросс-реалмовые и подклассовые крайние случаи. util.callbackify обращает promisify — полезно, когда нужно предоставить promise-функцию API в callback-стиле. util.MIMEType (Node 19+) разбирает и изменяет MIME-типы.
const util = require('util');
// type checks
util.isPromise(Promise.resolve()); // true
util.isFunction(() => {}); // true
util.types.isMap(new Map()); // true
util.types.isAsyncFunction(async () => {}); // true
util.types.isRegExp(/x/); // true
// reverse of promisify: promise -> error-first callback
const readFileCb = util.callbackify(require('fs/promises').readFile);
readFileCb('x.txt', 'utf8', (err, data) => {
if (err) console.error(err);
else console.log(data);
});
// MIME type utilities (Node 19+)
util.MIMEType.parse('text/html; charset=utf-8');nextTick против setImmediate
process.nextTick выполняется сразу после текущей синхронной операции, ДО ввода-вывода, поэтому рекурсивный nextTick может бесконечно морить I/O (цикл не продвигается). setImmediate выполняется после ввода-вывода, в фазе 'check'. Чтобы уступить циклу событий и дать ожидающему I/O завершиться, предпочитайте setImmediate; nextTick оставьте для очистки, которая должна произойти до любого I/O-callback.
// process.nextTick: runs BEFORE I/O, after the current op
process.nextTick(() => console.log('tick'));
// setImmediate: runs AFTER I/O events, in the 'check' phase
setImmediate(() => console.log('immediate'));
// setTimeout(0): runs in the timers phase, after nextTick
setTimeout(() => console.log('timeout'), 0);
// typical order in one loop turn:
// 1. current sync code
// 2. nextTick callbacks (can starve I/O!)
// 3. timers
// 4. I/O callbacks
// 5. setImmediate
// prefer setImmediate to yield to I/O; use nextTick for
// immediate post-sync cleanupСвязанные сниппеты Node.js
Copy-paste ready code for common tasks.
fs Module
Read, write, and watch files with promises and callbacks.
HTTP Server
Build an HTTP server with the http module and routing.
Streams
Pipe, transform, and consume streams efficiently.
EventEmitter
Emit and listen for custom events.
path Module
Join, resolve, and parse file paths cross-platform.
Buffers
Work with binary data using Buffer and TypedArrays.
Child Process
Spawn, exec, and fork external processes.
Async Patterns
Run promises in parallel, sequentially, and with limits.
Was this helpful?