原文地址https://blog.risingstack.com/node-js-best-practices-2017


使用ES2015

Last year we advised you to use ES2015 - however, a lot has changed since.

去年我们就建议你使用ES2015 - 但是还是有太多变化了。

Back then, Node.js v4 was the LTS version, and it had support for 57% of the ES2015 functionality. A year passed and ES2015 support grew to 99% with Node v6.

回到年初,Node.js V4还是LTS版,已经支持了57%的ES2015语法。一年过后,Node V6版本对ES2015支持度已经长到99%了。

If you are on the latest Node.js LTS version you don’t need babel anymore to use the whole feature set of ES2015. But even with this said, on the client side you’ll probably still need it!

如果你在使用最新的Node.jsLTS版本的话,你就不需要再使用babel来支持ES2015的所有语法了。但是虽然这样,浏览器端你可能还是需要使用的。

For more information on which Node.js version supports which ES2015 features, I’d recommend checking out node.green.

要查看更多的Node.js版本对ES2015支持度,我建议你看这个node.green

使用Promises

Promises are a concurrency primitive, first described in the 80s. Now they are part of most modern programming languages to make your life easier.

Promises是一个相当老的一个并发控制模型,第一次提出是在80年代。现在它成为了大部分现代编程语言的一部分,让你生活得更好。

Imagine the following example code that reads a file, parses it, and prints the name of the package. Using callbacks, it would look something like this:

看下面这个例子,读取文件,转化数据,输出pakcge的name值。如果使用回调,代码会是这样:

1
2
3
4
5
6
7
8
9
10
11
12
fs.readFile('./package.json', 'utf-8', function (err, data) {  
if (err) {
return console.log(err)
}

try {
data = JSON.parse(data)
} catch (ex) {
return console.log(ex)
}
console.log(data.name)
})

Wouldn’t it be nice to rewrite the snippet into something more readable? Promises help you with that:

如果把这个代码写成可读性更高的会怎么样?Promises可以做到这点:

1
2
3
4
5
6
fs.readFileAsync('./package.json').then(JSON.parse).then((data) => {  
console.log(data.name)
})
.catch((e) => {
console.error('error reading/parsing file', e)
})

Of course, for now, the fs API does not have an readFileAsync that returns a Promise. To make it work, you have to wrap it with a module like promisifyAll.

当然,现在fs接口并没有一个会返回Promise的readFileAsync方法。为了能够运行,必须使用promisifyAll之类的模块包装一下。

使用JavaScritp标准代码规范

When it comes to code style, it is crucial to have a company-wide standard, so when you have to change projects, you can be productive starting from day zero, without having to worry about building the build because of different presets.

说到代码规范,有一个公司内的标准是非常重要的,这样当你换了项目之后,你也能马上进行开发,而不需要因为不同的配置而担心项目构建。

At RisingStack we have incorporated the JavaScript Standard Style in all of our projects.

在RisingStack,我们把JavaScript标准代码规范编入到我们所有项目里。

With Standard, there is no decisions to make, no .eslintrc, .jshintrc, or .jscsrc files to manage. It just works. You can find the Standard rules here.

使用标准,我们就不需要做一些决定,没有.eslintrc.jshintrc,也没有.jscsrc需要处理。这个直接就能工作。你可以从这里找到标准规则

使用Docker —— 2017年容器生产就绪

You can think of Docker images as deployment artifacts - Docker containers wrap up a piece of software in a complete filesystem that contains everything it needs to run: code, runtime, system tools, system libraries – anything you can install on a server.

你可以把Docker作为部署神器 —— Docker容器在完整的文件系统中包裹了一点应用,包含了运行需要的所有东西:代码,运行时,系统工具,系统库 —— 任何你能在服务器上安装的东西。

But why should you start using Docker?

  • it enables you to run your applications in isolation,
  • as a conscience, it makes your deployments more secure,
  • Docker images are lightweight,
  • they enable immutable deployments,
  • and with them, you can mirror production environments locally.

但是为什么你要使用Docker呢?

  • 让你的应用运行在隔离的环境中;
  • 作为一个有道德的人,这个可以让部署更加安全;
  • Docker的镜像小;
  • 允许不可变的部署;
  • 有了它,可以在本地复制产品环境。

To get started with Docker, head over to the official getting started tutorial. Also, for orchestration we recommend checking out our Kubernetes best practices article.

开始使用Docker,可以看官方的开始指南。还有,对于业务流程我们建议可以参考我们的文章Kubernetes最佳实践

监控你的应用

If something breaks in your Node.js application, you should be the first one to know about it, not your customers.

如果你的Node.js应用挂掉了,你必须是第一个知道的,而不是你的用户。

One of the newer open-source solutions is Prometheus that can help you achieve this. Prometheus is an open-source systems monitoring and alerting toolkit originally built at SoundCloud. The only downside of Prometheus is that you have to set it up for you and host it for yourself.

最新的开源解决方案是Prometheus,它可以帮你完成这个。Prometheus是一个开源的监控报警工具,最开始构建在SoundCloud上的。Prometheus唯一的不足就是你要自己配置部署。

If you are looking for on out-of-the-box solution with support, Trace by RisingStack is a great solution developed by us.

如果你要找一个有技术支持的开箱即用的的解决方案,Trace by RisingStack是我们开发的一个非常棒的一个解决方法。

Trace will help you with

  • alerting,
  • memory and CPU profiling in production systems,
  • distributed tracing and error searching,
  • performance monitoring,
  • and keeping your npm packages secure!

Trace 能够帮你

  • 报警;
  • 线上产品内存与CPU性能分析;
  • 分布式的追踪与错误查询;
  • 性能监控;
  • 包含你的npm包安全。

后台进程使用消息传递机制

If you are using HTTP for sending messages, then whenever the receiving party is down, all your messages are lost. However, if you pick a persistent transport layer, like a message queue to send messages, you won’t have this problem.

如果你在用HTTP传递消息,一旦接受方挂了,那你所有的数据都会丢失。如果你使用一个持久传输层,比如消息队列来发送消息,你就不会有这个问题了。

If the receiving service is down, the messages will be kept, and can be processed later. If the service is not down, but there is an issue, processing can be retried, so no data gets lost.

如果接收服务挂掉了,这些小些会被保留,并且可以之后再处理。如果服务没有挂,但是出了一个问题,会重新进行处理,所以不会有数据丢失。

An example: you’d like to send out thousands of emails. In this case, you would just have to put some basic information like the target email address and the first name, and a background worker could easily put together the email’s content and send them out.

举一个例子:发送上千封邮件。这种情况,你只要把基本信息比如收件地址和收件人名字,后台任务可以轻松的把邮件合并到一起然后发送出去。

What’s really great about this approach is that you can scale it whenever you want, and no traffic will be lost. If you see that there are millions of emails to be sent out, you can add extra workers, and they can consume the very same queue.

这个方法真正好的地方在于无论什么时候你都可以改变数据的规模,而且不会有信息被丢失。例如你有几百万封的邮件要发送,你只需要增加额外的任务进程就可以了,他们会处理同一个队列。

You have lots of options for messaging queues:

你有非常多的消息队列选择:

使用最新的LTS版Node.js

To get the best of the two worlds (stability and new features) we recommend using the latest LTS (long-term support) version of Node.js. As of writing this article, it is version 6.9.2.

为了达到最佳的两个境界(稳定和新功能),我们建议你使用最新的LTS(long-term support)版Node.js。截至本文,最新版本为 6.9.2

To easily switch Node.js version, you can use nvm. Once you installed it, switching to LTS takes only two commands:

为了简单切换Node.js版本,你可以使用nvm。只要你安装了这个,切换到LTS版只需要两行命令:

1
2
nvm install 6.9.2  
nvm use 6.9.2

使用语义化的版本控制

We conducted a Node.js Developer Survey a few months ago, which allowed us to get some insights on how people use semantic versioning.

几个月前我们发起了一个Node.js开发者调查,这个调查让我们对大家如何使用语义化版本控制产生了一些见解。

Unfortunately, we found out that only 71% of our respondents uses semantic versioning when publishing/consuming modules. This number should be higher in our opinion - everyone should use it! Why? Because updating packages without semver can easily break Node.js apps.

可惜的是,我们发现只有71%的受调查者会在发布或者使用模块的时候使用了语义化的版本控制。在我们看来这个数字应该再高一些 —— 所有人都应该使用这个!为啥?因为缺少语义的更新包很容易的破坏Node.js应用。

对你的应用和模块进行版本控制时非常关键的——使用者必须要知道新版本的发布以及需要做哪些事来获取新版本。

Versioning your application / modules is critical - your consumers must know if a new version of a module is published and what needs to be done on their side to get the new version.

This is where semantic versioning comes into the picture. Given a version number MAJOR.MINOR.PATCH, increment the:

  • MAJOR version when you make incompatible API changes,
  • MINOR version when you add functionality (without breaking the API), and
  • PATCH version when you make backwards-compatible bug fixes.

这种情况下语义化版本控制应运而生。使用版本号格式 MAJOR.MINOR.PATCH

  • 增加MAJOR号,当出现不兼容的API改动;
  • 增加MINOR号,当增加了新的功能(没有破坏API)
  • 增加PATCH号,当完成了向前兼容的bug修复

npm also uses SemVer when installing your dependencies, so when you publish modules, always make sure to respect it. Otherwise, you can break others applications!

npm在安装依赖的时候也是用了语义化版本控制,所以当你发布模块的时候要遵守这个规则。否则,你可能会破坏其他应用。

保护你的应用安全

Securing your users and customers data should be one of your top priorities in 2017. In 2016 alone, hundreds of millions of user accounts were compromised as a result of low security.

保护你的用户与客户数据会是2017年最高优先级。仅在2016年,上亿的用户账号由于太低的安全性而受到威胁

To get started with Node.js Security, read our Node.js Security Checklist, which covers topics like:

  • Security HTTP Headers,
  • Brute Force Protection,
  • Session Management,
  • Insecure Dependencies,
  • or Data Validation.

开始注意Node.js的安全,可以阅读这篇文章Node.js安全注意事项,包含了这些话题:

  • 安全的HTTP头部,
  • 强力的保护,
  • session维护,
  • 不安全的依赖
  • 数据检验

After you’ve embraced the basics, check out my Node Interactive talk on Surviving Web Security with Node.js!

这些基本的都看完之后,可以再看一下我们的Node互动讨论Node.js中网络安全问题

使用Serverless架构

Serverless started with the introduction of AWS Lambda. Since then it is growing fast, with a blooming open-source community.

Serverless是由Aws Lambda引入的。从那之后Serverless发展地非常快,开源社区也迅速发展的。

In the next years, serverless will become a major factor for building new applications. If you’d like to stay on the edge, you should start learning it today.

接下来的几年,Serverless会成为构建应用的主要方式。如果你还在技术边缘,最好马上开始学习使用。

One of the most popular solutions is the Serverless Framework, which helps in deploying AWS Lambda functions.

最知名的解决方案之一就是Serverless Framework,它在发布部署AWS Lambda应用的时候可以发挥作用。

参加或者在各种交流会议发布演讲

Attending conferences and meetups are great ways to learn about new trends, use-cases or best practices. Also, it is a great forum to meet new people.

参加会议是非常好的获取新资讯,使用案例和最佳实践的方式。而且,这也是遇见新的人的非常好的方式。

To take it one step forward, I’d like to encourage you to speak at one of these events as well!

向前一小步,我非常鼓励你能在这些大会上演讲。

As public speaking is tough, and “imagine everyone’s naked” is the worst advice, I’d recommend checking out speaking.io for tips on public speaking!

公开演说还是相当难的,而且“把每个人想象成裸体”是最差的建议,所以我建议看一下speaking.io作为发表公开演说的参考。

在2017年成为更好的Node.js开发者

As 2017 will be the year of Node.js, we’d like to help you getting the most out of it!

因为2017会成为Node.js之年,我们非常希望你能成为他们中的一个。

We just launched a new study program called “Owning Node.js” which helps you to become confident in:

  • Async Programming with Node.js
  • Creating servers with Express
  • Using Databases with Node
  • Project Structuring and building scalable apps

我们刚启动了一个项目叫做“Owning Node.js”的项目,帮助你:

  • 使用Node.js进行异步编程
  • 使用Express创建服务
  • 在Node中使用数据库
  • 构建结构化的工程和可伸缩的应用

点评:这篇文章没啥干货,severless可以研究一下。居然还给自己插了好几条广告,真是讨厌,还是2016那篇写得好。