nodejs
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: 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
What this skill does
# Node.js Best Practices
> **Full Reference**: See [advanced.md](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
```typescript
// 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
```typescript
// 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)
```typescript
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
| Scenario | Use Instead |
|----------|-------------|
| Express.js framework | `backend-express` skill |
| NestJS framework | `backend-nestjs` skill |
| JavaScript/TypeScript syntax | `javascript` or `typescript` skills |
| Testing | `testing-vitest` or `testing-jest` skills |
| Database operations | Database-specific skills |
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Correct Approach |
|--------------|--------------|------------------|
| Blocking the event loop | Freezes all requests | Use async APIs or workers |
| Not handling rejections | Silent failures | Use process.on('unhandledRejection') |
| Synchronous file I/O | Blocks event loop | Use async fs methods |
| Unbounded caches | Memory leaks | Use LRU cache with limits |
| Not removing event listeners | Memory leaks | Use .off() or .removeListener() |
| Nested callbacks | Callback hell | Use async/await |
| Large sync JSON.parse | Blocks event loop | Stream parsing or workers |
| No concurrency limits | Resource exhaustion | Use p-limit or semaphores |
## Quick Troubleshooting
| Issue | Cause | Solution |
|-------|-------|----------|
| High event loop lag | Blocking operations | Profile with --inspect, use workers |
| Memory leak | Unbounded cache/listeners | Use heap snapshots, fix leaks |
| "EADDRINUSE" | Port already in use | Kill process or use different port |
| "EMFILE: too many open files" | File descriptor leak | Close files, increase ulimit |
| Process crashes on error | Uncaught exception | Add error handlers |
| Slow startup | Too many sync operations | Make initialization async |
| High CPU usage | Infinite loop or blocking | Profile with --cpu-prof |
| "MaxListenersExceededWarning" | Too many listeners | Remove 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
| Metric | Target |
|--------|--------|
| Event loop lag | < 100ms |
| Heap usage | < 70% of limit |
| Active handles | Stable |
| GC pause | < 100ms |
## Reference Documentation
- [TypeScript](../typescript/SKILL.md)
- [Performance](../../best-practices/performance/SKILL.md)
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.