Agent Skills
› cosmicstack-labs/mercury-agent-skills
› nodejs-patterns
nodejs-patterns
GitHub提供生产级 Node.js 后端开发的最佳实践,涵盖异步控制流、并行执行、错误处理机制、模块化设计规范以及集群部署和优雅关闭等生产环境加固策略。
Trigger Scenarios
编写高性能异步 Node.js 代码
配置 Express 全局错误处理中间件
设计高内聚低耦合的 Node.js 模块
优化 Node.js 应用的生产环境稳定性与监控
Install
npx skills add cosmicstack-labs/mercury-agent-skills --skill nodejs-patterns -g -y
SKILL.md
Frontmatter
{
"name": "nodejs-patterns",
"metadata": {
"tags": [
"nodejs",
"backend",
"javascript",
"async",
"server"
],
"author": "cosmicstack-labs",
"version": "1.0.0",
"category": "backend"
},
"description": "Async control flow, error handling, module design, streams, and production hardening"
}
Node.js Patterns
Production-grade Node.js backend patterns.
Async Patterns
Prefer Async/Await
// Good
async function getUser(id) {
const user = await db.findUser(id);
return user;
}
// Avoid raw callbacks or.then() chains
Parallel Execution
// Sequential (slow)
const user = await fetchUser(id);
const posts = await fetchPosts(id);
// Parallel (fast)
const [user, posts] = await Promise.all([
fetchUser(id),
fetchPosts(id),
]);
Error Handling
Global Handler
process.on('uncaughtException', (err) => {
console.error('Uncaught:', err);
// Graceful shutdown
server.close(() => process.exit(1));
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection:', reason);
});
Express Error Middleware
app.use((err, req, res, next) => {
const status = err.status || 500;
res.status(status).json({
error: err.message,
...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
});
});
Module Design
- Single responsibility per module
- Export a class or factory function, not plain objects
- Use dependency injection for testability
- Prefer CommonJS (require) or ESM (import), consistent throughout
Production Hardening
- Cluster mode for multi-core
- Process manager (PM2) with auto-restart
- Health check endpoints
- Graceful shutdown (SIGTERM handler)
- Memory limit monitoring
- Structured logging (pino/winston)
Version History
- 38e2523 Current 2026-07-05 19:36


