[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-021cda09-8e5c-44e7-bcd2-d1c6a0ba0f71":3,"$fW2AvB-poG6bSDtv5QlKv3cZZ_2d6TOUvwP5y5enaPeg":42},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":33},"021cda09-8e5c-44e7-bcd2-d1c6a0ba0f71","nodejs-best-practices","Node.js开发原则和决策。框架选择、异步模式、安全和架构。教授思考，而非复制。","cat_coding_backend","mod_coding","sickn33,coding","---\nname: nodejs-best-practices\ndescription: \"Node.js development principles and decision-making. Framework selection, async patterns, security, and architecture. Teaches thinking, not copying.\"\nrisk: unknown\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Node.js Best Practices\n\n> Principles and decision-making for Node.js development in 2025.\n> **Learn to THINK, not memorize code patterns.**\n\n## When to Use\nUse this skill when making Node.js architecture decisions, choosing frameworks, designing async patterns, or applying security and deployment best practices.\n\n---\n\n## ⚠️ How to Use This Skill\n\nThis skill teaches **decision-making principles**, not fixed code to copy.\n\n- ASK user for preferences when unclear\n- Choose framework\u002Fpattern based on CONTEXT\n- Don't default to same solution every time\n\n---\n\n## 1. Framework Selection (2025)\n\n### Decision Tree\n\n```\nWhat are you building?\n│\n├── Edge\u002FServerless (Cloudflare, Vercel)\n│   └── Hono (zero-dependency, ultra-fast cold starts)\n│\n├── High Performance API\n│   └── Fastify (2-3x faster than Express)\n│\n├── Enterprise\u002FTeam familiarity\n│   └── NestJS (structured, DI, decorators)\n│\n├── Legacy\u002FStable\u002FMaximum ecosystem\n│   └── Express (mature, most middleware)\n│\n└── Full-stack with frontend\n    └── Next.js API Routes or tRPC\n```\n\n### Comparison Principles\n\n| Factor | Hono | Fastify | Express |\n|--------|------|---------|---------|\n| **Best for** | Edge, serverless | Performance | Legacy, learning |\n| **Cold start** | Fastest | Fast | Moderate |\n| **Ecosystem** | Growing | Good | Largest |\n| **TypeScript** | Native | Excellent | Good |\n| **Learning curve** | Low | Medium | Low |\n\n### Selection Questions to Ask:\n1. What's the deployment target?\n2. Is cold start time critical?\n3. Does team have existing experience?\n4. Is there legacy code to maintain?\n\n---\n\n## 2. Runtime Considerations (2025)\n\n### Native TypeScript\n\n```\nNode.js 22+: --experimental-strip-types\n├── Run .ts files directly\n├── No build step needed for simple projects\n└── Consider for: scripts, simple APIs\n```\n\n### Module System Decision\n\n```\nESM (import\u002Fexport)\n├── Modern standard\n├── Better tree-shaking\n├── Async module loading\n└── Use for: new projects\n\nCommonJS (require)\n├── Legacy compatibility\n├── More npm packages support\n└── Use for: existing codebases, some edge cases\n```\n\n### Runtime Selection\n\n| Runtime | Best For |\n|---------|----------|\n| **Node.js** | General purpose, largest ecosystem |\n| **Bun** | Performance, built-in bundler |\n| **Deno** | Security-first, built-in TypeScript |\n\n---\n\n## 3. Architecture Principles\n\n### Layered Structure Concept\n\n```\nRequest Flow:\n│\n├── Controller\u002FRoute Layer\n│   ├── Handles HTTP specifics\n│   ├── Input validation at boundary\n│   └── Calls service layer\n│\n├── Service Layer\n│   ├── Business logic\n│   ├── Framework-agnostic\n│   └── Calls repository layer\n│\n└── Repository Layer\n    ├── Data access only\n    ├── Database queries\n    └── ORM interactions\n```\n\n### Why This Matters:\n- **Testability**: Mock layers independently\n- **Flexibility**: Swap database without touching business logic\n- **Clarity**: Each layer has single responsibility\n\n### When to Simplify:\n- Small scripts → Single file OK\n- Prototypes → Less structure acceptable\n- Always ask: \"Will this grow?\"\n\n---\n\n## 4. Error Handling Principles\n\n### Centralized Error Handling\n\n```\nPattern:\n├── Create custom error classes\n├── Throw from any layer\n├── Catch at top level (middleware)\n└── Format consistent response\n```\n\n### Error Response Philosophy\n\n```\nClient gets:\n├── Appropriate HTTP status\n├── Error code for programmatic handling\n├── User-friendly message\n└── NO internal details (security!)\n\nLogs get:\n├── Full stack trace\n├── Request context\n├── User ID (if applicable)\n└── Timestamp\n```\n\n### Status Code Selection\n\n| Situation | Status | When |\n|-----------|--------|------|\n| Bad input | 400 | Client sent invalid data |\n| No auth | 401 | Missing or invalid credentials |\n| No permission | 403 | Valid auth, but not allowed |\n| Not found | 404 | Resource doesn't exist |\n| Conflict | 409 | Duplicate or state conflict |\n| Validation | 422 | Schema valid but business rules fail |\n| Server error | 500 | Our fault, log everything |\n\n---\n\n## 5. Async Patterns Principles\n\n### When to Use Each\n\n| Pattern | Use When |\n|---------|----------|\n| `async\u002Fawait` | Sequential async operations |\n| `Promise.all` | Parallel independent operations |\n| `Promise.allSettled` | Parallel where some can fail |\n| `Promise.race` | Timeout or first response wins |\n\n### Event Loop Awareness\n\n```\nI\u002FO-bound (async helps):\n├── Database queries\n├── HTTP requests\n├── File system\n└── Network operations\n\nCPU-bound (async doesn't help):\n├── Crypto operations\n├── Image processing\n├── Complex calculations\n└── → Use worker threads or offload\n```\n\n### Avoiding Event Loop Blocking\n\n- Never use sync methods in production (fs.readFileSync, etc.)\n- Offload CPU-intensive work\n- Use streaming for large data\n\n---\n\n## 6. Validation Principles\n\n### Validate at Boundaries\n\n```\nWhere to validate:\n├── API entry point (request body\u002Fparams)\n├── Before database operations\n├── External data (API responses, file uploads)\n└── Environment variables (startup)\n```\n\n### Validation Library Selection\n\n| Library | Best For |\n|---------|----------|\n| **Zod** | TypeScript first, inference |\n| **Valibot** | Smaller bundle (tree-shakeable) |\n| **ArkType** | Performance critical |\n| **Yup** | Existing React Form usage |\n\n### Validation Philosophy\n\n- Fail fast: Validate early\n- Be specific: Clear error messages\n- Don't trust: Even \"internal\" data\n\n---\n\n## 7. Security Principles\n\n### Security Checklist (Not Code)\n\n- [ ] **Input validation**: All inputs validated\n- [ ] **Parameterized queries**: No string concatenation for SQL\n- [ ] **Password hashing**: bcrypt or argon2\n- [ ] **JWT verification**: Always verify signature and expiry\n- [ ] **Rate limiting**: Protect from abuse\n- [ ] **Security headers**: Helmet.js or equivalent\n- [ ] **HTTPS**: Everywhere in production\n- [ ] **CORS**: Properly configured\n- [ ] **Secrets**: Environment variables only\n- [ ] **Dependencies**: Regularly audited\n\n### Security Mindset\n\n```\nTrust nothing:\n├── Query params → validate\n├── Request body → validate\n├── Headers → verify\n├── Cookies → validate\n├── File uploads → scan\n└── External APIs → validate response\n```\n\n---\n\n## 8. Testing Principles\n\n### Test Strategy Selection\n\n| Type | Purpose | Tools |\n|------|---------|-------|\n| **Unit** | Business logic | node:test, Vitest |\n| **Integration** | API endpoints | Supertest |\n| **E2E** | Full flows | Playwright |\n\n### What to Test (Priorities)\n\n1. **Critical paths**: Auth, payments, core business\n2. **Edge cases**: Empty inputs, boundaries\n3. **Error handling**: What happens when things fail?\n4. **Not worth testing**: Framework code, trivial getters\n\n### Built-in Test Runner (Node.js 22+)\n\n```\nnode --test src\u002F**\u002F*.test.ts\n├── No external dependency\n├── Good coverage reporting\n└── Watch mode available\n```\n\n---\n\n## 9. Anti-Patterns to Avoid\n\n### ❌ DON'T:\n- Use Express for new edge projects (use Hono)\n- Use sync methods in production code\n- Put business logic in controllers\n- Skip input validation\n- Hardcode secrets\n- Trust external data without validation\n- Block event loop with CPU work\n\n### ✅ DO:\n- Choose framework based on context\n- Ask user for preferences when unclear\n- Use layered architecture for growing projects\n- Validate all inputs\n- Use environment variables for secrets\n- Profile before optimizing\n\n---\n\n## 10. Decision Checklist\n\nBefore implementing:\n\n- [ ] **Asked user about stack preference?**\n- [ ] **Chosen framework for THIS context?** (not just default)\n- [ ] **Considered deployment target?**\n- [ ] **Planned error handling strategy?**\n- [ ] **Identified validation points?**\n- [ ] **Considered security requirements?**\n\n---\n\n> **Remember**: Node.js best practices are about decision-making, not memorizing patterns. Every project deserves fresh consideration based on its requirements.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,177,578,"2026-05-16 13:31:01",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"编程开发","coding","mdi-code-braces","代码生成、调试、审查，提升开发效率",2,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":25,"skillCount":32,"createdAt":26},"后端开发","backend","mdi-server","API、数据库、服务端架构",296,[34],{"id":35,"skillId":4,"version":36,"fileName":37,"fileSize":38,"filePath":39,"fileHash":40,"manifest":41,"createdAt":19},"11a2f894-6a73-4078-9abb-99ca18bc5362","1.0.0","nodejs-best-practices.zip",3870,"uploads\u002Fskills\u002F021cda09-8e5c-44e7-bcd2-d1c6a0ba0f71\u002Fnodejs-best-practices.zip","45eecb08184426c9a610f58967f27ef35cdaeedad731d4a0ab2c37d369a569a4","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":8772}]",{"code":43,"message":44,"data":45},200,"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]