node-js
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNode.js
Node.js
Workflow
工作流
- Confirm Node.js runtime baseline and package manager strategy.
- Define repository structure and module boundaries.
- Select language/module approach (TypeScript vs JavaScript, ESM vs CJS).
- Establish dependency and supply-chain controls.
- Implement testing strategy and CI quality gates.
- Harden runtime behavior for performance and resilience.
- Apply OWASP-aligned security controls.
- Ship with observability and operations runbooks.
- 确认Node.js运行时基线及包管理器策略。
- 定义仓库结构与模块边界。
- 选择语言/模块方案(TypeScript vs JavaScript,ESM vs CJS)。
- 建立依赖与供应链管控机制。
- 落地测试策略与CI质量门禁。
- 强化运行时性能与韧性表现。
- 应用符合OWASP标准的安全管控措施。
- 搭配可观测性工具与运维手册交付。
Preflight (Ask / Check First)
前置检查(先询问/确认)
- Target active Node LTS line and hosting/runtime constraints.
- Service shape: API, worker, CLI, or hybrid.
- Repo model: single package vs monorepo.
- Build tooling and transpilation requirements.
- Expected traffic, latency SLOs, and failure budgets.
- Security/compliance requirements for dependencies and secrets.
- 目标活跃Node LTS版本及部署/运行时约束。
- 服务形态:API、工作进程、CLI或混合类型。
- 仓库模式:单包仓库 vs 单体仓库(monorepo)。
- 构建工具与转译需求。
- 预期流量、延迟SLO及故障预算。
- 依赖与密钥的安全/合规要求。
Operating Principles
运营原则
- Keep boundaries explicit between domain, transport, and infrastructure.
- Prefer deterministic builds with lockfiles and pinned toolchains.
- Keep async flows cancellable and timeout-aware.
- Standardize logging and error contracts across services.
- Measure performance before optimization.
- Document operational decisions near code and pipelines.
- 明确领域层、传输层与基础设施层的边界。
- 优先使用带锁文件和固定工具链的确定性构建。
- 确保异步流可取消且具备超时感知能力。
- 跨服务标准化日志与错误契约。
- 优化前先测量性能基准。
- 在代码与流水线附近记录运维决策。
Project Structure and Architecture
项目结构与架构
- Organize by feature/domain, not utility dumping grounds.
- Keep shared libraries small and versioned intentionally.
- In monorepos, enforce dependency boundaries and ownership.
- Keep entrypoints (,
api,worker) isolated.scheduler - Separate adapters (DB, HTTP, queue) from domain logic.
- 按功能/领域组织代码,而非堆砌工具类代码。
- 保持共享库体积小巧并进行有意版本化。
- 在单体仓库中,强制依赖边界与归属权管理。
- 隔离入口文件(、
api、worker)。scheduler - 将适配器(数据库、HTTP、队列)与领域逻辑分离。
Example Layout
示例布局
src/domain/*src/application/*src/infrastructure/*src/interfaces/http/*src/interfaces/queue/*test/*
src/domain/*src/application/*src/infrastructure/*src/interfaces/http/*src/interfaces/queue/*test/*
Language and Module Strategy
语言与模块策略
- Prefer modern Node features supported by chosen LTS.
- Choose ESM or CJS deliberately; avoid accidental mixing.
- Prefer TypeScript strict mode for medium/large codebases.
- Keep API surfaces explicit and typed.
- Avoid transpilation complexity without clear benefit.
- 优先选择所选LTS版本支持的现代Node特性。
- 谨慎选择ESM或CJS;避免意外混合使用。
- 中大型代码库优先使用TypeScript严格模式。
- 保持API接口明确且带类型定义。
- 无明确收益时避免转译复杂度。
Runtime Sanity Checks
运行时 sanity 检查
bash
node -v
npm -vbash
node --check src/index.jsbash
node -v
npm -vbash
node --check src/index.jsDependency and Supply-Chain Management
依赖与供应链管理
- Commit lockfiles and enforce deterministic install mode in CI.
- Prefer minimal dependency count and regular update cadence.
- Audit direct and transitive dependencies by exploitability.
- Keep private package publishing scoped and credential-protected.
- Document policy for semver ranges and upgrade windows.
- 提交锁文件并在CI中强制启用确定性安装模式。
- 优先减少依赖数量并保持定期更新节奏。
- 按可利用性审计直接与间接依赖。
- 私有包发布使用范围限定并保护凭证。
- 记录语义化版本范围与升级窗口期策略。
Testing and Release Workflow
测试与发布工作流
- Maintain layered tests: unit, integration, and system/e2e.
- Prefer for lightweight suites and use built-in reporters/watch mode when it simplifies CI and local feedback.
node:test - Add at least one CI lane with (or
NODE_PENDING_DEPRECATION=1) to catch upcoming runtime breaks early.--pending-deprecation - Keep CI fast for PR feedback; run heavy suites on merge/nightly.
- Enforce lint/type/test/build as required gates.
- Use semantic release/tagging conventions consistently.
- Keep changelog and rollback notes for production deploys.
- 维护分层测试:单元测试、集成测试、系统/端到端测试。
- 轻量级测试套件优先使用,当它能简化CI与本地反馈时,使用内置报告器/监听模式。
node:test - 至少添加一条CI流水线,启用(或
NODE_PENDING_DEPRECATION=1)以提前发现即将到来的运行时兼容性问题。--pending-deprecation - 保持PR反馈阶段的CI速度;在合并/夜间运行重型测试套件。
- 强制启用代码检查/类型检查/测试/构建作为必要的质量门禁。
- 持续使用语义化发布/标签规范。
- 为生产部署保留变更日志与回滚说明。
Typical Validation Commands
典型验证命令
bash
npm run lint
npm run test
npm run buildbash
npm run test:integration
npm audit --omit=devbash
npm run lint
npm run test
npm run buildbash
npm run test:integration
npm audit --omit=devPerformance and Scalability
性能与可扩展性
- Use async I/O and avoid blocking CPU in request paths.
- Offload CPU-heavy work to workers or external jobs.
- Profile event loop delay and memory under realistic load.
- Apply connection pooling and bounded concurrency.
- Implement backpressure and queue limits for burst traffic.
- 使用异步I/O,避免在请求路径中阻塞CPU。
- 将CPU密集型工作卸载到工作进程或外部任务。
- 在真实负载下分析事件循环延迟与内存使用情况。
- 应用连接池与有界并发控制。
- 为突发流量实现背压与队列限制。
Error Handling and Resilience
错误处理与韧性
- Use typed/domain errors with stable mapping to HTTP/queue responses.
- Treat unhandled promise rejections as fatal by default; set explicitly only with clear policy.
--unhandled-rejections - Apply timeouts/retries with jitter and idempotency controls.
- Guard against cascading failure with circuit-breaker patterns.
- Ensure graceful shutdown drains in-flight work.
- Keep fatal vs recoverable error policy explicit.
- 使用带类型/领域标识的错误,并稳定映射到HTTP/队列响应。
- 默认将未处理的Promise拒绝视为致命错误;仅在有明确策略时显式设置。
--unhandled-rejections - 应用带抖动与幂等性控制的超时/重试机制。
- 使用断路器模式防止级联故障。
- 确保优雅关闭时能处理完正在进行的工作。
- 明确区分致命错误与可恢复错误的处理策略。
Security Controls
安全管控
- Validate and sanitize all untrusted inputs.
- Keep secrets out of source and logs.
- Enforce authn/authz at boundary and domain levels.
- Use Node's permission model (,
--permission,--allow-fs-read) for high-risk jobs to reduce blast radius.--allow-fs-write - Apply secure headers and TLS posture for HTTP services.
- Protect dependency chain with scanning and provenance where possible.
- 验证并净化所有不可信输入。
- 避免将密钥存入代码与日志。
- 在边界层与领域层强制认证/授权。
- 对高风险任务使用Node的权限模型(、
--permission、--allow-fs-read)以缩小影响范围。--allow-fs-write - 为HTTP服务应用安全头与TLS配置。
- 尽可能通过扫描与溯源保护依赖链。
Environment Configuration
环境配置
- Use core dotenv support (and
process.loadEnvFile()) when your Node baseline supports it; prefer one parsing path per service.util.parseEnv() - Keep usage local/dev-oriented and inject production secrets through platform-native secret managers.
.env - Never rely on
.env; Node ignores it in env files by design.NODE_OPTIONS
- 当Node基线版本支持时,使用核心dotenv功能(和
process.loadEnvFile());每个服务优先使用单一解析路径。util.parseEnv() - 限制用于本地/开发环境,通过平台原生密钥管理器注入生产环境密钥。
.env - 永远不要依赖中的
.env;Node设计上会忽略环境文件中的该配置。NODE_OPTIONS
Observability and Operations
可观测性与运维
- Emit structured logs with correlation IDs.
- Capture metrics for latency, throughput, errors, and saturation.
- Instrument distributed tracing on critical request paths.
- Keep dashboards and SLO alerts tied to user-facing risk.
- Maintain incident runbooks and service ownership maps.
- 输出带关联ID的结构化日志。
- 捕获延迟、吞吐量、错误与饱和度指标。
- 在关键请求路径上实现分布式追踪。
- 将仪表盘与SLO告警和用户侧风险关联。
- 维护事件响应手册与服务归属映射。
Deployment and Runtime Operations
部署与运行时运维
- Use immutable artifacts and environment-specific config injection.
- Keep health endpoints meaningful (,
liveness).readiness - Validate startup probes and shutdown grace windows.
- Track config drift across environments.
- Exercise disaster-recovery drills and failover playbooks.
- 使用不可变制品与环境特定配置注入。
- 确保健康检查端点(、
liveness)有实际意义。readiness - 验证启动探测与优雅关闭窗口。
- 追踪跨环境的配置漂移。
- 执行灾难恢复演练与故障切换预案。
Data and Integration Boundaries
数据与集成边界
- Set explicit DB/query timeouts and pool limits.
- Keep migrations transactional and reversible when possible.
- Make external API retry behavior explicit per endpoint.
- Use idempotency keys where duplicate delivery is possible.
- 设置明确的数据库/查询超时与连接池限制。
- 尽可能保持迁移的事务性与可逆性。
- 为每个外部API端点明确重试行为。
- 在可能出现重复交付的场景使用幂等键。
Common Failure Modes
常见故障模式
- Unbounded async concurrency leading to resource exhaustion.
- Event-loop blocking work in hot request paths.
- Mixed module systems causing runtime loader errors.
- Depending on invalid
package.jsonfallback behavior that newer Node versions deprecate.main - CI passing with missing integration coverage.
- Dependency drift causing non-reproducible builds.
- Weak shutdown behavior dropping in-flight work.
- 无界异步并发导致资源耗尽。
- 热点请求路径中的事件循环阻塞工作。
- 混合模块系统导致运行时加载器错误。
- 依赖新版本Node弃用的
package.jsonfallback无效行为。main - CI通过但缺少集成测试覆盖。
- 依赖漂移导致构建不可复现。
- 弱关闭行为导致正在进行的工作丢失。
Definition of Done
完成标准
- Architecture and boundaries are clear and enforced.
- Build/test/release pipeline is deterministic.
- Performance and resilience have measured baselines.
- Security controls and dependency hygiene are active.
- Observability and operational runbooks are production-ready.
- 架构与边界清晰且已强制执行。
- 构建/测试/发布流水线具备确定性。
- 性能与韧性有可测量的基线。
- 安全管控与依赖规范处于生效状态。
- 可观测性与运维手册已准备好投入生产。
References
参考资料
references/node.js.md
references/node.js.md
Reference Index
参考索引
rg -n "Project structure|architecture|monorepo" references/node.js.mdrg -n "ESM|CommonJS|TypeScript|coding style" references/node.js.mdrg -n "Dependency|supply-chain|npm|Yarn|pnpm" references/node.js.mdrg -n "Testing|CI|release|changelog" references/node.js.mdrg -n "Performance|resilience|error handling" references/node.js.mdrg -n "OWASP|security|observability|deployment" references/node.js.md
rg -n "Project structure|architecture|monorepo" references/node.js.mdrg -n "ESM|CommonJS|TypeScript|coding style" references/node.js.mdrg -n "Dependency|supply-chain|npm|Yarn|pnpm" references/node.js.mdrg -n "Testing|CI|release|changelog" references/node.js.mdrg -n "Performance|resilience|error handling" references/node.js.mdrg -n "OWASP|security|observability|deployment" references/node.js.md
Quick Questions (When Stuck)
快速排查问题(遇到困境时)
- Is this a runtime bottleneck, architecture issue, or dependency issue?
- Can we reduce complexity by removing a dependency?
- Is this path bounded by CPU, I/O, or external service latency?
- What happens during shutdown under active load?
- Which metric proves this change improved reliability?
- 这是运行时瓶颈、架构问题还是依赖问题?
- 我们能否通过移除某个依赖来降低复杂度?
- 这个路径受限于CPU、I/O还是外部服务延迟?
- 高负载下关闭服务会发生什么?
- 哪个指标能证明此变更提升了可靠性?