Project Icon

nodebestpractices

Node.js开发最佳实践大全 助力性能安全与代码优化

该项目收录100余条Node.js最佳实践,内容全面涵盖项目架构、错误处理、代码风格、测试、部署和安全等核心领域。由行业专家持续更新维护,提供详细说明和代码示例,适合不同水平的开发者学习参考,有助于构建高质量、安全可靠的Node.js应用。

Node.js Best Practices

Node.js Best Practices


102 items Last update: January 3rd, 2024 Updated for Node 22.0.0

Follow us on Twitter! @nodepractices


Read in a different language: CNCN, FRFR, BRBR, RURU, PLPL, JAJA, EUEU (ESES, HEHE, KRKR and TRTR in progress! )


🎊 2024 edition is here!

  • 🛰 Modernized to 2024: Tons of text edits, new recommended libraries, and some new best practices

  • ✨ Easily focus on new content: Already visited before? Search for #new or #updated tags for new content only

  • 🔖 Curious to see examples? We have a starter: Visit Practica.js, our application example and boilerplate (beta) to see some practices in action



Welcome! 3 Things You Ought To Know First

1. You are reading dozens of the best Node.js articles - this repository is a summary and curation of the top-ranked content on Node.js best practices, as well as content written here by collaborators

2. It is the largest compilation, and it is growing every week - currently, more than 80 best practices, style guides, and architectural tips are presented. New issues and pull requests are created every day to keep this live book updated. We'd love to see you contributing here, whether that is fixing code mistakes, helping with translations, or suggesting brilliant new ideas. See our writing guidelines here

3. Best practices have additional info - most bullets include a 🔗Read More link that expands on the practice with code examples, quotes from selected blogs, and more information



By Yoni Goldberg

Learn with me: As a consultant, I engage with worldwide teams on various activities like workshops and code reviews. 🎉AND... Hold on, I've just launched my beyond-the-basics testing course, which is on a 🎁 limited-time sale until August 7th



Table of Contents

1. Project Architecture Practices (6)

  1.1 Structure your solution by components #strategic #updated
  1.2 Layer your components, keep the web layer within its boundaries #strategic #updated
  1.3 Wrap common utilities as packages, consider publishing
  1.4 Use environment aware, secure and hierarchical config #updated
  1.5 Consider all the consequences when choosing the main framework #new
  1.6 Use TypeScript sparingly and thoughtfully #new

2. Error Handling Practices (12)

  2.1 Use Async-Await or promises for async error handling
  2.2 Extend the built-in Error object #strategic #updated
  2.3 Distinguish operational vs programmer errors #strategic #updated
  2.4 Handle errors centrally, not within a middleware #strategic
  2.5 Document API errors using OpenAPI or GraphQL
  2.6 Exit the process gracefully when a stranger comes to town #strategic
  2.7 Use a mature logger to increase errors visibility #updated
  2.8 Test error flows using your favorite test framework #updated
  2.9 Discover errors and downtime using APM products
  2.10 Catch unhandled promise rejections #updated
  2.11 Fail fast, validate arguments using a dedicated library
  2.12 Always await promises before returning to avoid a partial stacktrace #new
  2.13 Subscribe to event emitters 'error' event #new

3. Code Style Practices (12)

  3.1 Use ESLint #strategic
  3.2 Use Node.js eslint extension plugins #updated
  3.3 Start a Codeblock's Curly Braces on the Same Line
  3.4 Separate your statements properly
  3.5 Name your functions
  3.6 Use naming conventions for variables, constants, functions and classes
  3.7 Prefer const over let. Ditch the var
  3.8 Require modules first, not inside functions
  3.9 Set an explicit entry point to a module/folder #updated
  3.10 Use the === operator
  3.11 Use Async Await, avoid callbacks #strategic
  3.12 Use arrow function expressions (=>)
  3.13 Avoid effects outside of functions #new

4. Testing And Overall Quality Practices (13)

  4.1 At the very least, write API (component) testing #strategic
  4.2 Include 3 parts in each test name #new
  4.3 Structure tests by the AAA pattern #strategic
  4.4 Ensure Node version is unified #new
  4.5 Avoid global test fixtures and seeds, add data per-test #strategic
  4.6 Tag your tests #advanced
  4.7 Check your test coverage, it helps to identify wrong test patterns
  4.8 Use production-like environment for e2e testing
  4.9 Refactor regularly using static analysis tools
  4.10 Mock responses of external HTTP services #advanced #new #advanced
  4.11 Test your middlewares in isolation
  4.12 Specify a port in production, randomize in testing #new
  4.13 Test the five possible outcomes #strategic #new

5. Going To Production Practices (19)

  5.1. Monitoring #strategic
  5.2. Increase the observability using smart logging #strategic
  5.3. Delegate anything possible (e.g. gzip, SSL) to a reverse proxy #strategic
  5.4. Lock dependencies
  5.5. Guard process uptime using the right tool
  5.6. Utilize all CPU cores
  5.7. Create a ‘maintenance endpoint’
  5.8. Discover the unknowns using APM products #advanced #updated
  5.9. Make your code production-ready
  5.10. Measure and guard the memory usage #advanced
  5.11. Get your frontend assets out of Node
  5.12. Strive to be stateless #strategic
  5.13. Use tools that automatically detect vulnerabilities
  5.14. Assign a transaction id to each log statement #advanced
  5.15. Set NODE_ENV=production
  5.16. Design automated, atomic and zero-downtime deployments #advanced
  5.17. Use an LTS release of Node.js
  5.18. Log to stdout, avoid specifying log destination within the app #updated
  5.19. Install your packages with npm ci #new

6. Security Practices (25)

  6.1. Embrace linter security rules
  6.2. Limit concurrent requests using a middleware
  6.3 Extract secrets from config files or use packages to encrypt them #strategic
  6.4. Prevent query injection vulnerabilities with ORM/ODM libraries #strategic
  6.5. Collection of generic security best practices
  6.6. Adjust the HTTP response headers for enhanced security
  6.7. Constantly and automatically inspect for vulnerable dependencies #strategic
  6.8. Protect Users' Passwords/Secrets using bcrypt or scrypt #strategic
  6.9. Escape HTML, JS and CSS output
  6.10. Validate incoming JSON schemas #strategic
  6.11. Support blocklisting JWTs
  6.12. Prevent brute-force attacks against authorization #advanced
  6.13. Run Node.js as non-root user
  6.14. Limit payload size using a reverse-proxy or a middleware
  6.15. Avoid JavaScript eval statements
  6.16. Prevent evil RegEx from overloading your single thread execution
  [6.17. Avoid module loading using a

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号