nodejs 实践项目

by Saurabh Rayakwar

通过索拉比·雷阿克瓦尔

NodeJS:最佳生产实践 (NodeJS: Best Practices for Production)

This is an attempt to enlist the most important practices for developing and deploying on NodeJs.

这是为了争取在NodeJ上进行开发和部署的最重要的实践。

I have been working on this technology for a while myself. I realize its huge potential and place in the development process. With tough competition from languages like Python and Golang, NodeJS has proven its utility in appropriate use cases.

我本人一直在研究这项技术。 我意识到它在发展过程中的巨大潜力和地位。 经过来自Python和Golang等语言的激烈竞争,NodeJS在适当的用例中证明了其实用性。

Before I delve into the best practices ?, I would like to do a brief introduction to what a microservice pattern is. Then take the conversation further from there.

在深入研究最佳实践?之前,我想简要介绍什么是微服务模式。 然后,从那里进一步进行对话。

那么,什么是微服务? (So, what are microservices?)

Microservices - also known as the microservice architecture - is an architectural style that structures an application as a collection of services that are:

微服务-也称为微服务架构-是一种架构样式,可将应用程序构造为以下服务的集合:

  • Highly maintainable and testable高度可维护和可测试
  • Loosely coupled松耦合
  • Independently deployable可独立部署
  • Organized around business capabilities.围绕业务功能进行组织。

The microservice architecture enables the continuous delivery/deployment of large, complex applications. It also enables an organization to evolve its technology stack.

微服务架构可实现大型复杂应用程序的连续交付/部署。 它还使组织能够发展其技术堆栈。

如何决定您是否需要微服务 (How to decide if you need microservices)

Initially, when you are just starting out to work on your MVP, you might not need to use microservices. The Y-axis scaling might not be your agenda right now. But when the product starts to mature and sometimes too early where you have to deal with scaling, the decomposition into functional modules makes more sense as the business itself is decomposing. This will be the right point to start looking into the microservices architecture pattern.

最初,当您刚开始在MVP上工作时,可能不需要使用微服务。 Y轴缩放现在可能不是您的议程。 但是,当产品开始成熟,有时甚至还为时过早,您不得不处理扩展问题时,随着业务本身的分解,分解为功能模块就变得更加有意义。 这将是开始研究微服务架构模式的正确时机。

A book that I highly recommend is by Chris Richardson here: http://bit.ly/2EmJDYt.

我强烈推荐的克里斯·理查森(Chris Richardson)的书在这里: http : //bit.ly/2EmJDYt 。

Microservices are most commonly considered while replacing a monolithic application that used to be pretty common until recently when containerization solutions like Docker started ruling the DevOps world. But more on that later.

微服务在替换过去一直很常见的单片应用程序时被普遍考虑,直到最近诸如Docker之类的容器化解决方案开始统治DevOps世界。 但是稍后会更多。

It would be unfair if I continue without mentioning Domain Driven Design (DDD). It is a very popular strategy for decomposing your product into functional modules. Hence it is very useful to create microservices.

如果我不提及域驱动设计(DDD),那将是不公平的。 将产品分解为功能模块是一种非常流行的策略。 因此,创建微服务非常有用。

那么,根据DDD,什么是域? (So, what is a domain as per DDD?)

Each problem that you are trying to solve is a domain.

您要解决的每个问题都是一个领域。

Each domain is subdivided into mutually exclusive bounded contexts. These contexts are nothing but separate areas of that particular problem.

每个域都细分为互斥的有界上下文。 这些上下文不过是该特定问题的单独区域。

In a microservice pattern, each bounded context correlates to a microservice. DDD patterns help you understand the complexity in the domain. For the domain model for each Bounded Context, you identify and define the entities, value objects, and aggregates that model your domain.

在微服务模式中,每个有界上下文都与微服务相关。 DDD模式可帮助您了解域的复杂性。 对于每个有界上下文的域模型,您可以识别并定义为域建模的实体,值对象和集合。

Depending on the complexity of your software you can choose the DDD principles or perform a simpler approach.

根据软件的复杂性,您可以选择DDD原理或执行更简单的方法。

The goal is to achieve a highly cohesive and loosely coupled domain model. For that follow this approach:

目标是实现高度凝聚力和松散耦合的领域模型。 为此,请遵循以下方法:

This was a brief intro on the DDD. To learn more about it, I highly recommend reading Eric Evans’s excellent book http://bit.ly/2Eoy17l.

这是DDD的简短介绍。 要了解更多信息,我强烈建议您阅读Eric Evans的出色著作http://bit.ly/2Eoy17l 。

Moving on.

继续。

I hope you are holding on with me. ?

我希望你能坚持下去。 ?

So from here on, I will talk more about practices specific to NodeJS. And what I mean is that microservices and DDD help you benchmark the true potential of NodeJS nevertheless. It’s complete in itself. How? We will see.

因此,从这里开始,我将更多地讨论特定于NodeJS的实践。 我的意思是,微服务和DDD仍然可以帮助您基准化NodeJS的真正潜力。 它本身就是完整的。 怎么样? 我们会看到。

使用NodeJ时要使用哪种设计模式 (Which Design Pattern to use while using NodeJs)

Design Patterns are about designing software using certain standards that are known to a number of developers.

设计模式是关于使用许多开发人员已知的某些标准设计软件。

There are various design patterns we can use. I would like to introduce and/or recap for developers who already know about a pattern called the Repository Pattern.

我们可以使用多种设计模式。 我想为已经了解一种称为“存储库模式”的模式的开发人员介绍和/或概述。

This pattern makes it easier to separate the MVC logic while also making it easier to handle model definition and model interaction with the rest of the logic.

这种模式使分离MVC逻辑更容易,同时也使处理模型定义和与其他逻辑的模型交互变得更容易。

It consists of:

它包括:

  1. Controller: It only handles the request and response and associated attributes. It will not have any business logic or model definition or model associations too. (folder name: controllers)

    控制器 :它仅处理请求和响应以及关联的属性。 它也将没有任何业务逻辑或模型定义或模型关联。 (文件夹名称:控制器)

  2. Service: It contains business logic for your microservice. The control passes from controller to a service. It’s a 1:1 relationship between a controller and its service and a 1: many relationships between service and repositories. (folder name: services)

    服务 :它包含您的微服务的业务逻辑。 控制从控制器传递到服务。 这是控制器与其服务之间的1:1关系,以及服务与存储库之间的1:许多关系。 (文件夹名称:services)

  3. Repository: It interacts with the models that are part of the model folder. Any query to the database through the model layer will be formed here. It will not have any business logic. (folder name: repositories)

    存储库 :它与属于模型文件夹的模型进行交互。 通过模型层对数据库的任何查询都将在此处形成。 它不会有任何业务逻辑。 (文件夹名称:存储库)

  4. Model: It contains the model definition, associations, virtual functions (eg. in mongoose)

    Model :包含模型定义,关联,虚函数(例如,在猫鼬中)

  5. Utilities: This will contain helper classes/functions that can be used as services. Eg: a Redis utility that has all the functions required to interact with Redis. (folder name: utilities)

    实用程序 :它将包含可用作服务的帮助程序类/功能。 例如:Redis实用程序,具有与Redis交互所需的所有功能。 (文件夹名称:实用程序)

  6. Test case: This will include unit test cases against controller methods to ensure maximum code coverage. (folder name: spec)

    测试用例 :这将包括针对控制器方法的单元测试用例,以确保最大的代码覆盖率。 (文件夹名称:spec)

To read more on this, you can refer to this link: http://bit.ly/2TrSyRS

要了解更多信息,请参考以下链接: http : //bit.ly/2TrSyRS

好的,告诉我有关集群模块的信息 (Ok, Tell me about cluster modules)

A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.

Node.js的单个实例在单个线程中运行。 为了利用多核系统,用户有时会希望启动Node.js进程集群来处理负载。

The cluster module allows easy creation of child processes that all share server ports.

群集模块允许轻松创建所有共享服务器端口的子进程。

Please note that it’s ideal to use one process per container while using Docker containerization for deployment through microservices. Hence, cluster modules aren’t useful when using docker-ization.

请注意,在使用Docker容器化通过微服务进行部署时,理想的情况是每个容器使用一个进程。 因此,在使用docker-ization时,群集模块没有用。

如何处理NodeJS中的控制流 (How to handle control flow in NodeJS)

While using callbacks or promises, the following libraries could be useful:

在使用回调或承诺时,以下库可能会有用:

  1. Async (https://www.npmjs.com/package/async)

    异步( https://www.npmjs.com/package/async )

  2. Vasync( with better tracking of operation) https://www.npmjs.com/package/vasync

    Vasync(具有更好的操作跟踪) https://www.npmjs.com/package/vasync

  3. Bluebird ( handle promises eg. Promise.all etc.) https://www.npmjs.com/package/bluebird

    蓝鸟(履行承诺,例如Promise.all等) https://www.npmjs.com/package/bluebird

和循环? (And Loops?)

  • Series loop: executing each step one by one in order序列循环:依次一步一步执行每个步骤
  • Delayed loop: loop with a timeout延迟循环:超时循环
  • Parallel loop: collecting all promises in a loop and execute in parallel并行循环:在循环中收集所有promise并并行执行

还有哪些有用的整理工具? (And what are some useful linting tools?)

Linting tools analyze your code statically (without running it). They identify potential bugs or dangerous patterns. Patterns like the use of undeclared variables, or “case” statements inside a switch without a “break” statement.

整理工具静态分析您的代码(无需运行)。 他们确定潜在的错误或危险模式。 模式如使用未声明的变量,或在交换机中使用“ case”语句而不使用“ break”语句。

Enabling strict mode on your codebase with ‘use strict’ can help your code fail fast if the JavaScript parser can identify a leaked global or similar bad behaviour.

如果JavaScript解析器可以识别泄漏的全局或类似不良行为,则在代码库上使用“ use strict”启用严格模式可以帮助您的代码快速失败。

Examples of linters are Javascript lint and JS lint.

短绒的示例是Javascript短绒和JS短绒。

好的,我们如何处理日志记录? (Ok, how do we handle Logging?)

Some commonly used npm packages are:

一些常用的npm软件包是:

  • Winston (https://www.npmjs.com/package/winston)温斯顿(https://www.npmjs.com/package/winston)
  • Bunyan (https://www.npmjs.com/package/bunyan)Bunyan(https://www.npmjs.com/package/bunyan)

Possible logging format:

可能的日志记录格式:

For distributed systems like microservices, you would like to explore distributed tracing using ZipKin etc.

对于微服务等分布式系统,您想使用ZipKin等探索分布式跟踪。

A note on NPM packages : You should use a package only if it solves a problem for you that you can’t solve yourself. Regularly perform npm audits to find critical issues with your npm dependencies.

关于NPM软件包的说明:仅当软件包为您解决了自己无法解决的问题时,才应使用该软件包。 定期执行npm审核,以查找有关npm依赖项的关键问题。

处理未捕获的异常 (Handling uncaught exceptions)

By default, Node.js handles such exceptions by printing the stack trace to stderr and exiting with code 1, overriding any previously set process.exitCode

默认情况下,Node.js通过将堆栈跟踪信息打印到stderr并以代码1退出来处理此类异常,从而覆盖任何先前设置的process.exitCode

Note: Adding a handler for the 'uncaughtException' event overrides this default behaviour.

注意:为'uncaughtException'事件添加处理程序将覆盖此默认行为。

Alternatively, change the process.exitCode in the 'uncaughtException' handler which will result in the process exiting with the provided exit code. Otherwise, in the presence of such a handler, the process will exit with 0.

或者,在“ uncaughtException”处理程序中更改process.exitCode,这将导致进程使用提供的退出代码退出。 否则,在存在此类处理程序的情况下,该过程将以0退出。

process.exit(0) – successful termination process.exit(1) – unsuccessful termination

process.exit(0)–成功终止process.exit(1)–不成功终止

处理未处理的拒绝 (Handling unhandled rejections)

Promises are ubiquitous in Node.js code and sometimes chained to a very long list of functions that return promises and so on.

Promise在Node.js代码中无处不在,有时会链接到很长的返回诺言的函数列表等。

Not using a proper .catch(…) rejection handler will cause an unhandledRejection event to be emitted. If not properly caught and inspected, you may rob yourself of your only chance to detect and possibly fix the problem.

不使用适当的.catch(...)拒绝处理程序将导致发出unhandledRejection事件。 如果未正确捕获和检查,您可能会失去发现和解决问题的唯一机会。

额外提示: (Extra Tip:)

console.time()和console.timeEnd() (console.time() and console.timeEnd())

The console object has time() and timeEnd() methods that help with analyzing the performance of pieces of your code.

控制台对象具有time()和timeEnd()方法,可帮助您分析代码段的性能。

This is not a solution for production but it can be used when you don’t have better tools.

这不是生产解决方案,但是当您没有更好的工具时可以使用它。

Thank you very much for your time.Sign Up For My Newsletter

非常感谢您的宝贵时间。 订阅我的时事通讯

Other wonderful articles on similar topic(s) :

关于相似主题的其他精彩文章:

  1. https://microservices.io ?

    https://microservices.io ?

  2. https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/ddd-oriented-microservice

    https://docs.microsoft.com/zh-cn/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/ddd-directional-microservice

翻译自: https://www.freecodecamp.org/news/nodejs-best-practices-for-production-5b173983d14b/

nodejs 实践项目

nodejs 实践项目_NodeJS:最佳生产实践相关推荐

  1. nodejs 实践:express 最佳实践(五) connect解析

    nodejs 实践:express 最佳实践(五) connect解析 nodejs 发展很快,从 npm 上面的包托管数量就可以看出来.不过从另一方面来看,也是反映了 nodejs 的基础不稳固,需 ...

  2. nodejs 实践:express 最佳实践(六) express 自省获得所有的路由

    nodejs 实践:express 最佳实践(六) express 自省获得所有的路由 某些情况下,你需要知道你的应用有多少路由,这在 express 中没有方法可以.因此我这边曲线了一下,做成了一个 ...

  3. 公司项目NODEJS实践0.3[ mongo / session ...]

    一.前言 ⋅⋅⋅书接上回,我们搭建了WEB服务端路由.模板等功能,完成了register 通过ajax与后端的通信,今天主要完成数据与mongodb的存取,实现注册 / 登录 / 退出功能 ⋅⋅⋅DE ...

  4. 最佳 开源 人脸识别算法_开源项目的最佳社会结构是什么?

    最佳 开源 人脸识别算法 代码审查是一种实践,可促进开源项目中的快速协作,知识共享和最高质量. 代码审查的社会结构是项目的定义特征. 开源项目的最佳社会结构是什么? 在本文中,我们通过分析三个常见模型 ...

  5. python项目实践_python实践项目

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 文章节选自<机器学习--python实践>文末评论赠送本书,欢迎留言 ...

  6. Node.js 单元测试:我要写测试 - Mocha - Nodejs开源项目里怎么样写测试、CI和代码测试覆盖率

    -------------------------------------- 单元测试Express/NodeJs 个人理解, 1,如果不是测试http请求的单元测试,用Mocha, Chai等基本够 ...

  7. centos运行jar包需要的环境_Centos7服务器下启动jar包项目的最佳方法

    前言 在linux上运行jar包谁都会啊.为什么我还要单独拎出来讲呢.细心的朋友可能已经在标题中发现关键词Centos7和最佳方式. 这就说明我不是随便写点东西水一篇博客的ヾ(◍°∇°◍)ノ゙ 首先C ...

  8. Cognitive Inference:认知推理下的常识知识库资源、常识推理测试评估与中文实践项目索引...

    作者 | 刘焕勇 责编 | 李雪敬 出品 | CSDN博客 CognitiveInference Cognitive Inference,认知推理.常识知识库.常识推理与常识推理评估的系统项目,以现有 ...

  9. 认知推理下的常识知识库资源、常识测试评估与中文实践项目索引

    作者 | 刘焕勇 责编 | 李雪敬 出品 | CSDN博客 Cognitive Inference Cognitive Inference,认知推理.常识知识库.常识推理与常识推理评估的系统项目,以现 ...

最新文章

  1. All firmware and drivers for HP ESX servers
  2. HashSet 与TreeSet和LinkedHashSet的区别
  3. java 其他文件转pdf_java 其他文件转成pdf java生成pdf
  4. jQuery遍历(1)
  5. IE6/7和IE8/9(怪异模式)浮动元素折行Bug
  6. MyBatis 配置文件 用户密码加密存储
  7. river mongodb mysql_mongodb与mysql的应用场景?
  8. Codeforces Round #243 (Div. 1)
  9. 企业发展如何启动云的力量
  10. 何建坤:实施能源革命战略 促绿色低碳发展
  11. OFFICE技术讲座:边框的3D与方框的区别
  12. mysql recovery_MySQL Recovery
  13. sprintf_s函数用法
  14. 如何修改 WordPress 的用户默认头像?
  15. 汇编编写正弦函数代码
  16. 用计算机解决线性代数,线性代数问题计算机应用.doc
  17. 丘成桐:数理与人文(官方完整版PDF下载)(公号回复“丘成桐数学”下载PDF典型资料,欢迎转发、赞赏支持科普)
  18. MIUI12 Google play无法下载chrome及没有快捷方式的解决方法
  19. python虚拟机:pvm
  20. Golang 调用MySQL存储过程

热门文章

  1. 课程目标 java 1615308884
  2. 0309随堂笔记 银行转帐功能 对向封装 1615278206
  3. 循环打印三角形 java 0913
  4. python-列表包字典-根据字典的某一个键的值来进行排序
  5. django-学生列表页的制作
  6. Laravel中使用Eloquent时给查询的字段设置别名
  7. Anti-debugging Skills in APK
  8. PHPUnit-断言
  9. 为什么选择 npm script?
  10. ORACLE 如何产生一个随机数