Node.js runtime best practices. Covers event loop, async patterns, streams, worker threads, memory management, and production optimization. USE WHEN: user mentions "node.js", "event loop", "streams", "worker threads", asks about "process.nextTick", "memory leaks", "cluster mode", "async patterns" DO NOT USE FOR: reviewing existing Node code - use `review/nodejs`, which covers event loop, stream and process defects that have no diagnostic DO NOT USE FOR: Express/NestJS frameworks - use framework-specific skills DO NOT USE FOR: Language syntax - use `javascript` or `typescript` skills DO NOT USE FOR: Package management - use npm/pnpm/yarn skills

GitHub
Install command
npx skhub add claude-dev-suite/nodejs
Markdown
SKILL.md

Node.js Best Practices

Full Reference: See advanced.md for worker pool pattern, memory management, cluster mode, graceful shutdown, and performance flags.

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: nodejs for comprehensive documentation.

Event Loop

Phases

   ┌───────────────────────────┐
┌─>│           timers          │  ← setTimeout, setInterval
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │  ← I/O callbacks
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           poll            │  ← incoming I/O
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │           check           │  ← setImmediate
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │
   └───────────────────────────┘

Priority Order

sync code > process.nextTick > Promises (microtasks) > timers > setImmediate

Don't Block the Event Loop

// BAD - blocks event loop
function hashSync(data: string): string {
  return crypto.pbkdf2Sync(data, 'salt', 100000, 64, 'sha512').toString('hex');
}

// GOOD - use async version
async function hashAsync(data: string): Promise<string> {
  return new Promise((resolve, reject) => {
    crypto.pbkdf2(data, 'salt', 100000, 64, 'sha512', (err, key) => {
      if (err) reject(err);
      else resolve(key.toString('hex'));
    });
  });
}

Async Patterns

// GOOD - parallel execution
const [users, posts] = await Promise.all([
  fetchUsers(),
  fetchPosts()
]);

// BAD - sequential when parallel is possible
const users = await fetchUsers();
const posts = await fetchPosts(); // waits unnecessarily

// Handle unhandled rejections
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection:', reason);
});

Streams (Pipeline)

import { pipeline } from 'stream/promises';
import { createReadStream, createWriteStream } from 'fs';
import { createGzip } from 'zlib';

// GOOD - handles errors and cleanup
await pipeline(
  createReadStream('input.txt'),
  createGzip(),
  createWriteStream('output.txt.gz')
);

When NOT to Use This Skill

ScenarioUse Instead
Express.js frameworkbackend-express skill
NestJS frameworkbackend-nestjs skill
JavaScript/TypeScript syntaxjavascript or typescript skills
Testingtesting-vitest or testing-jest skills
Database operationsDatabase-specific skills

Anti-Patterns

Anti-PatternWhy It's BadCorrect Approach
Blocking the event loopFreezes all requestsUse async APIs or workers
Not handling rejectionsSilent failuresUse process.on('unhandledRejection')
Synchronous file I/OBlocks event loopUse async fs methods
Unbounded cachesMemory leaksUse LRU cache with limits
Not removing event listenersMemory leaksUse .off() or .removeListener()
Nested callbacksCallback hellUse async/await
Large sync JSON.parseBlocks event loopStream parsing or workers
No concurrency limitsResource exhaustionUse p-limit or semaphores

Quick Troubleshooting

IssueCauseSolution
High event loop lagBlocking operationsProfile with --inspect, use workers
Memory leakUnbounded cache/listenersUse heap snapshots, fix leaks
"EADDRINUSE"Port already in useKill process or use different port
"EMFILE: too many open files"File descriptor leakClose files, increase ulimit
Process crashes on errorUncaught exceptionAdd error handlers
Slow startupToo many sync operationsMake initialization async
High CPU usageInfinite loop or blockingProfile with --cpu-prof
"MaxListenersExceededWarning"Too many listenersRemove old listeners

Checklist

Development

  • Use async/await over callbacks
  • Handle all Promise rejections
  • Use streams for large data
  • Limit concurrent operations
  • Remove event listeners when done

Production

  • Use cluster mode or PM2
  • Implement graceful shutdown
  • Set appropriate heap size
  • Monitor memory usage
  • Use connection pooling
  • Enable keep-alive for HTTP

Metrics

MetricTarget
Event loop lag< 100ms
Heap usage< 70% of limit
Active handlesStable
GC pause< 100ms

Reference Documentation

Discovery
Tags

No tags published for this skill.

Version
Latest version metadata

Version

v2026.09.24

Published

Sep 24, 2026

Category

Uncategorized

License

MIT

Source path

skills/languages/nodejs

Default branch

main

Latest commit

9496306

Tree SHA

fe4e2f1