nodejs-patterns
Use when the user asks about Node.js streams and backpressure, stream.pipeline, worker threads, typed EventEmitter, AbortController, bounded Promise…
от j4flmao★ 47 звёзд на GitHub
Установить nodejs-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Node.js Patterns
Purpose
Implement production-grade Node.js patterns — streams with backpressure, typed event emitters, worker threads for CPU-bound work, DI containers, error classification, and async flow control.
Agent Protocol
Trigger
User request includes: Node.js stream, Node.js event emitter, Node.js worker thread, Node.js DI, Node.js error pattern, Node.js async, Node.js backpressure, Node.js event loop.
Input Context
- Node.js version (18+, 20+, 22+)
- Pattern needed (Streams, Workers, DI, Events, Errors)
- Runtime constraints (memory, CPU, concurrency)
Output Artifact
Code examples for the requested pattern. Compress output — no preamble, no postamble.
Response Format
Pattern: {streams | worker pool | DI | typed events | error hierarchy | async flow}
Why: {constraint it addresses}
Code: {minimal complete TypeScript}
Pitfalls: {backpressure, leaks, unhandled rejections}
Completion Criteria
- Stream pipeline with backpressure handling
- Typed event emitter with TypeScript generics
- Worker thread pool with message protocol
- DI container with scoped lifetimes
- Error classification hierarchy with Zod validation
Max Response Length
4096 tokens
Architecture Decision Trees
Streams vs Buffers vs Generators
| Criterion | Streams | Buffers | Async Generators |
|---|---|---|---|
| Memory | Constant (chunked) | Full dataset | Constant (lazy) |
| Backpressure | Built-in | Manual | Pull-based (automatic) |
| Piping | .pipe() or pipeline() |
Manual buffer copy | for await...of |
| Error handling | pipeline() with callback | try/catch | try/catch in loop |
| Use case | Large files, network IO | Small payloads, transforms | Lazy iteration |
Decision: Large data processing → Streams. In-memory transforms → Buffers. Pull-based iteration → Async Generators.
Worker Threads vs Cluster vs Child Process
| Criterion | Worker Threads | Cluster | Child Process |
|---|---|---|---|
| Shared memory | SharedArrayBuffer | No | No |
| IPC | Message passing | Built-in HTTP round-robin | stdio/pipe |
| Use case | CPU-bound tasks | HTTP load balancing | System commands |
| Module isolation | Same module | Same code | Separate binary |
| Overhead | Low | Medium | High |
Decision: CPU-bound parallel computation → Worker Threads. Multi-core HTTP serving → Cluster. Running external commands → Child Process.
Workflow
Step 1: Stream Pipeline with Backpressure
// src/streams/transform.ts
import { pipeline, Transform, Writable, Readable } from 'node:stream';
import { promisify } from 'node:util';
const pipelineAsync = promisify(pipeline);
// Backpressure-aware transform
class JsonlParser extends Transform {
private buffer = '';
_transform(chunk: Buffer, _encoding: string, callback: Function) {
this.buffer += chunk.toString();
const lines = this.buffer.split('\n');
this.buffer = lines.pop() || '';
for (const line of lines) {
if (line.trim()) {
try {
const parsed = JSON.parse(line);
this.push(parsed);
} catch { /* skip invalid lines */ }
}
}
callback();
}
_flush(callback: Function) {
if (this.buffer.trim()) {
try {
this.push(JSON.parse(this.buffer));
} catch { /* skip */ }
}
callback();
}
}
// Usage with backpressure
async function processLargeFile(inputPath: string, outputPath: string) {
await pipelineAsync(
fs.createReadStream(inputPath, { highWaterMark: 64 * 1024 }),
new JsonlParser(),
new Transform({
objectMode: true,
transform(chunk, _encoding, callback) {
callback(null, transformRecord(chunk));
},
}),
fs.createWriteStream(outputPath),
);
}
Step 2: Typed Event Emitter
// src/events/typed-emitter.ts
type EventMap = {
'user:created': { id: string; email: string };
'user:updated': { id: string; changes: string[] };
'order:placed': { orderId: string; amount: number };
'error': { code: string; message: string };
};
export class TypedEventEmitter {
private emitter = new EventEmitter();
on<K extends keyof EventMap>(event: K, listener: (payload: EventMap[K]) => void): this {
this.emitter.on(event, listener);
return this;
}
emit<K extends keyof EventMap>(event: K, payload: EventMap[K]): boolean {
return this.emitter.emit(event, payload);
}
once<K extends keyof EventMap>(event: K, listener: (payload: EventMap[K]) => void): this {
this.emitter.once(event, listener);
return this;
}
off<K extends keyof EventMap>(event: K, listener: (payload: EventMap[K]) => void): this {
this.emitter.off(event, listener);
return this;
}
}
// Usage
const events = new TypedEventEmitter();
events.on('user:created', ({ id, email }) => {
sendWelcomeEmail(email);
trackAnalytics('user_signup', id);
});
Step 3: Worker Thread Pool
``
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/code-organization.md
- references/express-patterns.md
- references/node-testing.md
- references/nodejs-async-patterns.md
- references/nodejs-di.md
- references/nodejs-error-handling.md
- references/nodejs-streams-patterns.md
- references/nodejs-streams.md
FAQ
Что делает скилл nodejs-patterns?
Use when the user asks about Node.js streams and backpressure, stream.pipeline, worker threads, typed EventEmitter, AbortController, bounded Promise concurrency or DI with awilix. Produces Node runtime pattern code. Not for project structure (use nodejs-architecture).
Как установить скилл nodejs-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл nodejs-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
AnthropicGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
claude-api
AnthropicReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
algorithmic-art
AnthropicCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
mcp-integration
AnthropicThis skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…