[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FAY8X20EFPJSFSVMHCN27V":3,"skill-same:01M7FAY8X20EFPJSFSVMHCN27V":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":35,"commitSha":36,"skillDirectory":37,"forksCount":38,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":6,"ownerDescription":41,"updatedAt":42,"install":43,"resources":56},"01M7FAY8X20EFPJSFSVMHCN27V","nodejs",null,"Use when building or operating a plain Node.js \u002F Express 5 backend service: project layout, async correctness, central error middleware, fail-fast config, graceful shutdown on SIGTERM. NOT DI modules\u002Fproviders\u002Fguards (that is `nestjs`), NOT the type system or tsconfig (that is `typescript`), NOT REST contract design (that is `api-design`).","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Fnodejs\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: nodejs\ndescription: \"Use when building or operating a plain Node.js \u002F Express 5 backend service: project layout, async correctness, central error middleware, fail-fast config, graceful shutdown on SIGTERM. NOT DI modules\u002Fproviders\u002Fguards (that is `nestjs`), NOT the type system or tsconfig (that is `typescript`), NOT REST contract design (that is `api-design`).\"\ntags: [nodejs, express, backend, async, error-handling]\nrecommends: [nestjs, typescript, api-design, error-handling, postgresdb]\norigin: risco\n---\n\n# Node.js backend services\n\nStand up a plain Node.js HTTP\u002FJSON service — `node:http` or Express 5 — that a person can read, test, and operate without a DI framework. This skill is about the runtime and the request lifecycle: how to lay out the code, how to keep async correct, how errors become status codes, how config fails fast, and how the process dies cleanly. The contract shape, the type system, and the data layer live elsewhere (see the boundary below).\n\n## Boundary\n\n- The app is built around `@Module` \u002F `@Injectable` \u002F DI providers, guards, interceptors, pipes, exception filters → [`nestjs`](..\u002Fnestjs\u002FSKILL.md). Nest starts the moment the DI container appears; route away then, do not half-build it here.\n- Pure TypeScript type system, generics, `tsconfig` → [`typescript`](..\u002Ftypescript\u002FSKILL.md). This skill uses TS but does not teach types.\n- REST resource modeling, versioning, pagination, status-code semantics (framework-agnostic) → [`api-design`](..\u002Fapi-design\u002FSKILL.md). This skill *wires* the handlers; api-design decides the contract. Cross-cutting error taxonomy → [`error-handling`](..\u002Ferror-handling\u002FSKILL.md).\n- Schema, queries, connection pool, migrations → [`postgresdb`](..\u002Fpostgresdb\u002FSKILL.md) \u002F [`prisma-orm`](..\u002Fprisma-orm\u002FSKILL.md) \u002F [`drizzle-orm`](..\u002Fdrizzle-orm\u002FSKILL.md). *Calling* a repository stays here; designing the table does not.\n- Containerizing \u002F shipping → [`docker`](..\u002Fdocker\u002FSKILL.md) \u002F [`deployment`](..\u002Fdeployment\u002FSKILL.md). Choosing the logging\u002Fmetrics\u002Ftracing stack → [`observability`](..\u002Fobservability\u002FSKILL.md). This skill emits structured logs and a shutdown hook; it does not own the pipeline.\n\n## Decide first\n\nPick the runtime shape before writing code — the wrong choice is expensive to undo.\n\n| Situation | Choice | Why |\n| --- | --- | --- |\n| Needs DI\u002Fmodules, large team, heavy cross-cutting | route to [`nestjs`](..\u002Fnestjs\u002FSKILL.md) | Don't reinvent a DI container by hand |\n| Small\u002Fmedium JSON API, want middleware + routing | Express 5 | Mature, async errors auto-forward (v5) |\n| One tiny endpoint, zero deps, a healthcheck | `node:http` | No dependency surface to maintain |\n| A library, not a server | not this skill | No request lifecycle to manage |\n\nDefaults for a new service: pin **Node 24 (Active LTS)** in `engines.node`; Node 22 is Maintenance LTS; Node 26 is Current (released 2026-05-05, enters LTS Oct 2026) — adopt it only if you want Temporal\u002FV8 14.6 and can track Current. Write **ESM** for new code (`\"type\": \"module\"`), CommonJS only when a hard dependency forces it.\n\n```jsonc\n\u002F\u002F package.json\n{\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=24\" },\n  \"scripts\": {\n    \"dev\": \"node --watch src\u002Fserver.ts\",\n    \"test\": \"node --test\"\n  }\n}\n```\n\n## Project layout\n\nConcrete tree. The names are conventions, not magic — but the split is load-bearing.\n\n```text\nsrc\u002F\n  app.ts          # build + return the Express app; NEVER calls listen()\n  server.ts       # imports app, listens, owns SIGTERM\u002Fshutdown\n  config\u002F\n    env.ts        # validate process.env once, export a typed `config`\n  routes\u002F\n    users.ts      # router only: path → controller\n  controllers\u002F\n    users.ts      # parse request, call service, shape response\n  services\u002F\n    users.ts      # business logic, no req\u002Fres objects\n  repositories\u002F\n    users.ts      # data access; the only layer that touches the DB\n  errors\u002F\n    app-error.ts  # AppError\u002FHttpError with status + code\n```\n\n**Rule — separate app construction from `listen()`.** `app.ts` builds and returns the app; `server.ts` binds the port and owns shutdown. Why: tests import `app` and exercise routes in-process without binding a port, so they run fast and in parallel.\n\n```ts\n\u002F\u002F Bad: index.ts listens at import time — untestable, double-binds in tests\nconst app = express();\napp.get(\"\u002Fhealth\", (_req, res) => res.json({ ok: true }));\napp.listen(3000); \u002F\u002F side effect on import\n\n\u002F\u002F Good: app.ts\nexport function buildApp() {\n  const app = express();\n  app.get(\"\u002Fhealthz\", (_req, res) => res.json({ ok: true }));\n  return app; \u002F\u002F no listen here\n}\n```\n\n## Async rules\n\nEvery async mistake here is a latent production incident, not a style nit.\n\n- **Await or return every promise.** A floating promise is a latent process crash — since Node 15 an unhandled rejection terminates the process by default. The error happens later, detached from its handler.\n- **Never mix callback + promise styles.** Promisify once at the boundary (`util.promisify` or `fs\u002Fpromises`) and stay in promises after that. Half-converted code swallows errors.\n- **`Promise.all` for independent work; sequential `await` only for true dependencies.** Awaiting independent calls one by one wastes wall-clock time.\n- **Use `AbortSignal.timeout(ms)` for per-operation deadlines** and thread the signal into `fetch`\u002FDB\u002Flong ops. Compose with `AbortController` so shutdown can cancel in-flight work (see graceful shutdown).\n- **Never rely on a global `unhandledRejection` handler as control flow.** Log and exit there if anything; do not use it to keep running.\n\n```ts\n\u002F\u002F Bad: forgotten await — the rejection floats and crashes later, error lost\nfunction handler(req, res) {\n  saveAudit(req.body);          \u002F\u002F returns a promise nobody awaits\n  res.json({ ok: true });       \u002F\u002F responds before save resolves\u002Frejects\n}\n\n\u002F\u002F Good: await it (Express 5 forwards a throw to the error middleware)\nasync function handler(req, res) {\n  await saveAudit(req.body);\n  res.json({ ok: true });\n}\n```\n\n## Error handling\n\nThis is the core, and the most common bug. In **Express 5 an async handler that rejects or throws is auto-forwarded to the error middleware** — no `try\u002Fcatch + next(err)` wrapper, no `asyncHandler`. Source: Express 5 migration guide and the framework's own router tests (a value-less `Promise.reject()` becomes an Error with message `Rejected promise`).\n\n- Define one `AppError` (or `HttpError`) carrying `status` and `code`. Throw it from services; controllers don't translate.\n- Register **exactly one 4-arg `(err, req, res, next)` error middleware, LAST**, after every route. **Arity is what makes Express treat it as an error handler** — a 3-arg function is a normal middleware no matter what you name it. Order still matters in v5.\n- A 404 fallthrough handler goes *just before* the error middleware.\n- Map known errors → their status; unknown → 500; **never leak the stack or raw message in production.**\n\n```ts\n\u002F\u002F errors\u002Fapp-error.ts\nexport class AppError extends Error {\n  constructor(public status: number, public code: string, message: string) {\n    super(message);\n  }\n}\n\n\u002F\u002F app.ts — registration ORDER (routes → 404 → error handler)\napp.use(\"\u002Fusers\", usersRouter);\n\napp.use((_req, res) => res.status(404).json({ code: \"not_found\" }));\n\n\u002F\u002F LAST, exactly 4 args — this is the error handler\napp.use((err, _req, res, _next) => {\n  const status = err instanceof AppError ? err.status : 500;\n  const code = err instanceof AppError ? err.code : \"internal_error\";\n  if (status >= 500) logger.error({ err }, \"unhandled\");\n  res.status(status).json({\n    code,\n    message: status \u003C 500 ? err.message : \"Internal Server Error\",\n    ...(process.env.NODE_ENV !== \"production\" && { stack: err.stack }),\n  });\n});\n```\n\n```ts\n\u002F\u002F Bad: the symptom \"async route throws but client gets 200 empty body\"\napp.use((err, _req, res, _next) => { \u002F* error handler *\u002F });  \u002F\u002F registered FIRST\napp.get(\"\u002Fusers\u002F:id\", async (req, res) => {\n  const u = await findUser(req.params.id);   \u002F\u002F throws NotFound\n  res.json(u);                                \u002F\u002F never reached; no handler after → hangs\u002Fempties\n});\n```\n\nThe error handler placed before the route never sees the throw, so the response is whatever was half-written. Put it last. See [`references\u002Fexpress5-migration.md`](references\u002Fexpress5-migration.md) for the full v4→5 breaking-change checklist, the middleware-order diagram, and the legacy v4 `asyncHandler` wrapper.\n\n## Config & secrets\n\nValidate `process.env` once at boot, fail fast, and export a typed `config` object. **A missing variable should crash at startup, not at 3am on first use.** Ban scattered `process.env.X` reads throughout the codebase — they hide the contract and defeat the boot check.\n\n```ts\n\u002F\u002F config\u002Fenv.ts — hand-rolled or zod\u002Fenvalid; the point is one gate\nimport { z } from \"zod\";\nconst schema = z.object({\n  PORT: z.coerce.number().default(3000),\n  DATABASE_URL: z.string().url(),\n  NODE_ENV: z.enum([\"development\", \"test\", \"production\"]).default(\"development\"),\n});\nexport const config = schema.parse(process.env); \u002F\u002F throws → process won't start\n```\n\n## Graceful shutdown\n\nOn SIGTERM the orchestrator gives you a brief window to finish. Drop nothing.\n\n1. Flip readiness to **not-ready** so the load balancer stops routing new traffic.\n2. `server.close()` — stop accepting new connections, let in-flight requests finish.\n3. Abort long-running work via a shared `AbortController` (the signal you threaded into ops).\n4. Close the DB pool and other resources.\n5. `process.exit(0)`, with a force-exit timer as a backstop if drain stalls.\n\nExpose `\u002Fhealthz` (liveness — is the process up) separately from `\u002Freadyz` (readiness — should it receive traffic). They answer different questions; conflating them causes both false restarts and dropped requests during deploys. The complete copy-pasteable `server.ts` — signal handlers, `AbortController`, readiness gate, force-exit backstop — lives in [`references\u002Fgraceful-shutdown.md`](references\u002Fgraceful-shutdown.md).\n\n```ts\n\u002F\u002F server.ts (sketch — full version in references\u002F)\nconst controller = new AbortController();\nconst server = buildApp().listen(config.PORT);\n\nfunction shutdown() {\n  ready = false;                       \u002F\u002F \u002Freadyz now 503\n  server.close(() => process.exit(0)); \u002F\u002F drain, then exit\n  controller.abort();                  \u002F\u002F cancel in-flight long ops\n  setTimeout(() => process.exit(1), 10_000).unref(); \u002F\u002F backstop\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n```\n\n## Testing\n\nNode 24 ships a built-in test runner — `node:test` with `node --test` — so a backend needs no external runner for unit\u002Fintegration tests, and `node --watch` for dev. **Import `app` from `app.ts` and hit it directly** (supertest or `undici`); never start the live server in a test. That is exactly why `app.ts` doesn't call `listen()`.\n\n```ts\nimport { test } from \"node:test\";\nimport assert from \"node:assert\u002Fstrict\";\nimport request from \"supertest\";\nimport { buildApp } from \"..\u002Fsrc\u002Fapp.ts\";\n\ntest(\"404 returns the error contract\", async () => {\n  const res = await request(buildApp()).get(\"\u002Fnope\");\n  assert.equal(res.status, 404);\n  assert.equal(res.body.code, \"not_found\");\n});\n```\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Do instead |\n| --- | --- | --- |\n| Floating promise (no `await`\u002F`return`) | Unhandled rejection crashes the process (Node 15+), error detached | Await or return every promise |\n| Error middleware with 3 args or not last | Express never treats it as an error handler; throws fall through | 4 args `(err,req,res,next)`, registered LAST |\n| Reading `process.env.X` everywhere | Missing var fails at 3am, contract is invisible | Validate once in `config\u002Fenv.ts`, export typed `config` |\n| `listen()` inside `app.ts` | Side effect on import; tests bind a port \u002F double-listen | `app.ts` returns app, `server.ts` listens |\n| `catch (e) {}` then continue | Swallows the failure, masks the bug | Re-throw, or map to an `AppError` |\n| `process.exit()` without draining | Drops in-flight requests on deploy | SIGTERM → `server.close()` → abort → exit |\n| Global `unhandledRejection` as control flow | Hides bugs, leaves process in a bad state | Log + exit there; fix the floating promise |\n| Assuming Express 4 defaults | v5: `urlencoded` `extended:false`, `static` `dotfiles:\"ignore\"` | Read [`references\u002Fexpress5-migration.md`](references\u002Fexpress5-migration.md) |\n| Leaking stack\u002Fmessage in prod | Information disclosure | Stack only when `NODE_ENV !== \"production\"` |\n\n## Verify\n\n`scripts\u002Fverify.sh` statically lints a produced repo for these rules (4-arg error handler last, no `listen()` in `app.ts`, `engines.node` supported, floating-promise heuristic). Advisory; hard-fails only on `listen()` in `app.ts` or a missing error handler.\n","# Node.js backend services\n\nStand up a plain Node.js HTTP\u002FJSON service — `node:http` or Express 5 — that a person can read, test, and operate without a DI framework. This skill is about the runtime and the request lifecycle: how to lay out the code, how to keep async correct, how errors become status codes, how config fails fast, and how the process dies cleanly. The contract shape, the type system, and the data layer live elsewhere (see the boundary below).\n\n## Boundary\n\n- The app is built around `@Module` \u002F `@Injectable` \u002F DI providers, guards, interceptors, pipes, exception filters → [`nestjs`](..\u002Fnestjs\u002FSKILL.md). Nest starts the moment the DI container appears; route away then, do not half-build it here.\n- Pure TypeScript type system, generics, `tsconfig` → [`typescript`](..\u002Ftypescript\u002FSKILL.md). This skill uses TS but does not teach types.\n- REST resource modeling, versioning, pagination, status-code semantics (framework-agnostic) → [`api-design`](..\u002Fapi-design\u002FSKILL.md). This skill *wires* the handlers; api-design decides the contract. Cross-cutting error taxonomy → [`error-handling`](..\u002Ferror-handling\u002FSKILL.md).\n- Schema, queries, connection pool, migrations → [`postgresdb`](..\u002Fpostgresdb\u002FSKILL.md) \u002F [`prisma-orm`](..\u002Fprisma-orm\u002FSKILL.md) \u002F [`drizzle-orm`](..\u002Fdrizzle-orm\u002FSKILL.md). *Calling* a repository stays here; designing the table does not.\n- Containerizing \u002F shipping → [`docker`](..\u002Fdocker\u002FSKILL.md) \u002F [`deployment`](..\u002Fdeployment\u002FSKILL.md). Choosing the logging\u002Fmetrics\u002Ftracing stack → [`observability`](..\u002Fobservability\u002FSKILL.md). This skill emits structured logs and a shutdown hook; it does not own the pipeline.\n\n## Decide first\n\nPick the runtime shape before writing code — the wrong choice is expensive to undo.\n\n| Situation | Choice | Why |\n| --- | --- | --- |\n| Needs DI\u002Fmodules, large team, heavy cross-cutting | route to [`nestjs`](..\u002Fnestjs\u002FSKILL.md) | Don't reinvent a DI container by hand |\n| Small\u002Fmedium JSON API, want middleware + routing | Express 5 | Mature, async errors auto-forward (v5) |\n| One tiny endpoint, zero deps, a healthcheck | `node:http` | No dependency surface to maintain |\n| A library, not a server | not this skill | No request lifecycle to manage |\n\nDefaults for a new service: pin **Node 24 (Active LTS)** in `engines.node`; Node 22 is Maintenance LTS; Node 26 is Current (released 2026-05-05, enters LTS Oct 2026) — adopt it only if you want Temporal\u002FV8 14.6 and can track Current. Write **ESM** for new code (`\"type\": \"module\"`), CommonJS only when a hard dependency forces it.\n\n```jsonc\n\u002F\u002F package.json\n{\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=24\" },\n  \"scripts\": {\n    \"dev\": \"node --watch src\u002Fserver.ts\",\n    \"test\": \"node --test\"\n  }\n}\n```\n\n## Project layout\n\nConcrete tree. The names are conventions, not magic — but the split is load-bearing.\n\n```text\nsrc\u002F\n  app.ts          # build + return the Express app; NEVER calls listen()\n  server.ts       # imports app, listens, owns SIGTERM\u002Fshutdown\n  config\u002F\n    env.ts        # validate process.env once, export a typed `config`\n  routes\u002F\n    users.ts      # router only: path → controller\n  controllers\u002F\n    users.ts      # parse request, call service, shape response\n  services\u002F\n    users.ts      # business logic, no req\u002Fres objects\n  repositories\u002F\n    users.ts      # data access; the only layer that touches the DB\n  errors\u002F\n    app-error.ts  # AppError\u002FHttpError with status + code\n```\n\n**Rule — separate app construction from `listen()`.** `app.ts` builds and returns the app; `server.ts` binds the port and owns shutdown. Why: tests import `app` and exercise routes in-process without binding a port, so they run fast and in parallel.\n\n```ts\n\u002F\u002F Bad: index.ts listens at import time — untestable, double-binds in tests\nconst app = express();\napp.get(\"\u002Fhealth\", (_req, res) => res.json({ ok: true }));\napp.listen(3000); \u002F\u002F side effect on import\n\n\u002F\u002F Good: app.ts\nexport function buildApp() {\n  const app = express();\n  app.get(\"\u002Fhealthz\", (_req, res) => res.json({ ok: true }));\n  return app; \u002F\u002F no listen here\n}\n```\n\n## Async rules\n\nEvery async mistake here is a latent production incident, not a style nit.\n\n- **Await or return every promise.** A floating promise is a latent process crash — since Node 15 an unhandled rejection terminates the process by default. The error happens later, detached from its handler.\n- **Never mix callback + promise styles.** Promisify once at the boundary (`util.promisify` or `fs\u002Fpromises`) and stay in promises after that. Half-converted code swallows errors.\n- **`Promise.all` for independent work; sequential `await` only for true dependencies.** Awaiting independent calls one by one wastes wall-clock time.\n- **Use `AbortSignal.timeout(ms)` for per-operation deadlines** and thread the signal into `fetch`\u002FDB\u002Flong ops. Compose with `AbortController` so shutdown can cancel in-flight work (see graceful shutdown).\n- **Never rely on a global `unhandledRejection` handler as control flow.** Log and exit there if anything; do not use it to keep running.\n\n```ts\n\u002F\u002F Bad: forgotten await — the rejection floats and crashes later, error lost\nfunction handler(req, res) {\n  saveAudit(req.body);          \u002F\u002F returns a promise nobody awaits\n  res.json({ ok: true });       \u002F\u002F responds before save resolves\u002Frejects\n}\n\n\u002F\u002F Good: await it (Express 5 forwards a throw to the error middleware)\nasync function handler(req, res) {\n  await saveAudit(req.body);\n  res.json({ ok: true });\n}\n```\n\n## Error handling\n\nThis is the core, and the most common bug. In **Express 5 an async handler that rejects or throws is auto-forwarded to the error middleware** — no `try\u002Fcatch + next(err)` wrapper, no `asyncHandler`. Source: Express 5 migration guide and the framework's own router tests (a value-less `Promise.reject()` becomes an Error with message `Rejected promise`).\n\n- Define one `AppError` (or `HttpError`) carrying `status` and `code`. Throw it from services; controllers don't translate.\n- Register **exactly one 4-arg `(err, req, res, next)` error middleware, LAST**, after every route. **Arity is what makes Express treat it as an error handler** — a 3-arg function is a normal middleware no matter what you name it. Order still matters in v5.\n- A 404 fallthrough handler goes *just before* the error middleware.\n- Map known errors → their status; unknown → 500; **never leak the stack or raw message in production.**\n\n```ts\n\u002F\u002F errors\u002Fapp-error.ts\nexport class AppError extends Error {\n  constructor(public status: number, public code: string, message: string) {\n    super(message);\n  }\n}\n\n\u002F\u002F app.ts — registration ORDER (routes → 404 → error handler)\napp.use(\"\u002Fusers\", usersRouter);\n\napp.use((_req, res) => res.status(404).json({ code: \"not_found\" }));\n\n\u002F\u002F LAST, exactly 4 args — this is the error handler\napp.use((err, _req, res, _next) => {\n  const status = err instanceof AppError ? err.status : 500;\n  const code = err instanceof AppError ? err.code : \"internal_error\";\n  if (status >= 500) logger.error({ err }, \"unhandled\");\n  res.status(status).json({\n    code,\n    message: status \u003C 500 ? err.message : \"Internal Server Error\",\n    ...(process.env.NODE_ENV !== \"production\" && { stack: err.stack }),\n  });\n});\n```\n\n```ts\n\u002F\u002F Bad: the symptom \"async route throws but client gets 200 empty body\"\napp.use((err, _req, res, _next) => { \u002F* error handler *\u002F });  \u002F\u002F registered FIRST\napp.get(\"\u002Fusers\u002F:id\", async (req, res) => {\n  const u = await findUser(req.params.id);   \u002F\u002F throws NotFound\n  res.json(u);                                \u002F\u002F never reached; no handler after → hangs\u002Fempties\n});\n```\n\nThe error handler placed before the route never sees the throw, so the response is whatever was half-written. Put it last. See [`references\u002Fexpress5-migration.md`](references\u002Fexpress5-migration.md) for the full v4→5 breaking-change checklist, the middleware-order diagram, and the legacy v4 `asyncHandler` wrapper.\n\n## Config & secrets\n\nValidate `process.env` once at boot, fail fast, and export a typed `config` object. **A missing variable should crash at startup, not at 3am on first use.** Ban scattered `process.env.X` reads throughout the codebase — they hide the contract and defeat the boot check.\n\n```ts\n\u002F\u002F config\u002Fenv.ts — hand-rolled or zod\u002Fenvalid; the point is one gate\nimport { z } from \"zod\";\nconst schema = z.object({\n  PORT: z.coerce.number().default(3000),\n  DATABASE_URL: z.string().url(),\n  NODE_ENV: z.enum([\"development\", \"test\", \"production\"]).default(\"development\"),\n});\nexport const config = schema.parse(process.env); \u002F\u002F throws → process won't start\n```\n\n## Graceful shutdown\n\nOn SIGTERM the orchestrator gives you a brief window to finish. Drop nothing.\n\n1. Flip readiness to **not-ready** so the load balancer stops routing new traffic.\n2. `server.close()` — stop accepting new connections, let in-flight requests finish.\n3. Abort long-running work via a shared `AbortController` (the signal you threaded into ops).\n4. Close the DB pool and other resources.\n5. `process.exit(0)`, with a force-exit timer as a backstop if drain stalls.\n\nExpose `\u002Fhealthz` (liveness — is the process up) separately from `\u002Freadyz` (readiness — should it receive traffic). They answer different questions; conflating them causes both false restarts and dropped requests during deploys. The complete copy-pasteable `server.ts` — signal handlers, `AbortController`, readiness gate, force-exit backstop — lives in [`references\u002Fgraceful-shutdown.md`](references\u002Fgraceful-shutdown.md).\n\n```ts\n\u002F\u002F server.ts (sketch — full version in references\u002F)\nconst controller = new AbortController();\nconst server = buildApp().listen(config.PORT);\n\nfunction shutdown() {\n  ready = false;                       \u002F\u002F \u002Freadyz now 503\n  server.close(() => process.exit(0)); \u002F\u002F drain, then exit\n  controller.abort();                  \u002F\u002F cancel in-flight long ops\n  setTimeout(() => process.exit(1), 10_000).unref(); \u002F\u002F backstop\n}\nprocess.on(\"SIGTERM\", shutdown);\nprocess.on(\"SIGINT\", shutdown);\n```\n\n## Testing\n\nNode 24 ships a built-in test runner — `node:test` with `node --test` — so a backend needs no external runner for unit\u002Fintegration tests, and `node --watch` for dev. **Import `app` from `app.ts` and hit it directly** (supertest or `undici`); never start the live server in a test. That is exactly why `app.ts` doesn't call `listen()`.\n\n```ts\nimport { test } from \"node:test\";\nimport assert from \"node:assert\u002Fstrict\";\nimport request from \"supertest\";\nimport { buildApp } from \"..\u002Fsrc\u002Fapp.ts\";\n\ntest(\"404 returns the error contract\", async () => {\n  const res = await request(buildApp()).get(\"\u002Fnope\");\n  assert.equal(res.status, 404);\n  assert.equal(res.body.code, \"not_found\");\n});\n```\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Do instead |\n| --- | --- | --- |\n| Floating promise (no `await`\u002F`return`) | Unhandled rejection crashes the process (Node 15+), error detached | Await or return every promise |\n| Error middleware with 3 args or not last | Express never treats it as an error handler; throws fall through | 4 args `(err,req,res,next)`, registered LAST |\n| Reading `process.env.X` everywhere | Missing var fails at 3am, contract is invisible | Validate once in `config\u002Fenv.ts`, export typed `config` |\n| `listen()` inside `app.ts` | Side effect on import; tests bind a port \u002F double-listen | `app.ts` returns app, `server.ts` listens |\n| `catch (e) {}` then continue | Swallows the failure, masks the bug | Re-throw, or map to an `AppError` |\n| `process.exit()` without draining | Drops in-flight requests on deploy | SIGTERM → `server.close()` → abort → exit |\n| Global `unhandledRejection` as control flow | Hides bugs, leaves process in a bad state | Log + exit there; fix the floating promise |\n| Assuming Express 4 defaults | v5: `urlencoded` `extended:false`, `static` `dotfiles:\"ignore\"` | Read [`references\u002Fexpress5-migration.md`](references\u002Fexpress5-migration.md) |\n| Leaking stack\u002Fmessage in prod | Information disclosure | Stack only when `NODE_ENV !== \"production\"` |\n\n## Verify\n\n`scripts\u002Fverify.sh` statically lints a produced repo for these rules (4-arg error handler last, no `listen()` in `app.ts`, `engines.node` supported, floating-promise heuristic). Advisory; hard-fails only on `listen()` in `app.ts` or a missing error handler.\n",{"name":5,"tags":24,"origin":29,"recommends":30,"description":7},[5,25,26,27,28],"express","backend","async","error-handling","risco",[31,32,33,28,34],"nestjs","typescript","api-design","postgresdb","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","06-前端与设计\u002Fnodejs",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill nodejs",{"tool":49,"command":50},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill nodejs",{"tool":52,"command":53},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill nodejs","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Fnodejs\u002FSKILL.md",true,[57,63,67,71],{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"evals\u002Fcases.yaml","REFERENCE","参考文档",2740,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Fnodejs\u002Fevals\u002Fcases.yaml",{"path":64,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":65,"sourceHtmlUrl":66},"evals\u002FREADME.md",732,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Fnodejs\u002Fevals\u002FREADME.md",{"path":68,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":69,"sourceHtmlUrl":70},"references\u002Fexpress5-migration.md",2815,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Fnodejs\u002Freferences\u002Fexpress5-migration.md",{"path":72,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fgraceful-shutdown.md",3119,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Fnodejs\u002Freferences\u002Fgraceful-shutdown.md",[76,83,88,95,102,109],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":84,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]