Merge pull request #568 from contributorpw/patch-reaction-of-changes-09_19

Russian translation. Reaction to recent changes 2019/09
This commit is contained in:
Yoni Goldberg
2019-10-04 08:36:55 +03:00
committed by GitHub
10 changed files with 151 additions and 9 deletions

View File

@ -752,6 +752,15 @@
"contributions": [
"content"
]
},
{
"login": "deyvisonrocha",
"name": "Deyvison Rocha",
"avatar_url": "https://avatars2.githubusercontent.com/u/686067?v=4",
"profile": "http://deyvisonrocha.com",
"contributions": [
"content"
]
}
],
"projectName": "nodebestpractices",

View File

@ -114,6 +114,7 @@ Thanks goes to these wonderful people who have contributed to this repository!
<td align="center"><a href="https://github.com/ryanouyang"><img src="https://avatars2.githubusercontent.com/u/360426?v=4" width="100px;" alt="ryan ouyang"/><br /><sub><b>ryan ouyang</b></sub></a><br /><a href="#content-ryanouyang" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/shabeer-mdy"><img src="https://avatars0.githubusercontent.com/u/26842535?v=4" width="100px;" alt="Shabeer"/><br /><sub><b>Shabeer</b></sub></a><br /><a href="#content-shabeer-mdy" title="Content">🖋</a></td>
<td align="center"><a href="https://github.com/halfzebra"><img src="https://avatars1.githubusercontent.com/u/3983879?v=4" width="100px;" alt="Eduard Kyvenko"/><br /><sub><b>Eduard Kyvenko</b></sub></a><br /><a href="#content-halfzebra" title="Content">🖋</a></td>
<td align="center"><a href="http://deyvisonrocha.com"><img src="https://avatars2.githubusercontent.com/u/686067?v=4" width="100px;" alt="Deyvison Rocha"/><br /><sub><b>Deyvison Rocha</b></sub></a><br /><a href="#content-deyvisonrocha" title="Content">🖋</a></td>
</tr>
</table>

View File

@ -330,15 +330,15 @@ const count = 2 // tenta executar 2(), mas 2 não é uma função
### Exemplo de Código
```javascript
// for class name we use UpperCamelCase
// para classes nós usamos UpperCamelCase
class SomeClassExample {}
// for const names we use the const keyword and lowerCamelCase
// para nomes de constantes nós usamos a palavra const e lowerCamelCase
const config = {
key: 'value'
};
// for variables and functions names we use lowerCamelCase
// para nomes de variáveis e funções nós usamos lowerCamelCase
let someVariableExample = 'value';
function doSomething() {}
```

View File

@ -1028,11 +1028,24 @@ All statements above will return false if used with `===`
<p align="right"><a href="#table-of-contents">⬆ Return to top</a></p>
# `7. Performance Best Practices`
# `7. Draft: Performance Best Practices`
## Our contributors are working on this section. [Would you like to join?](https://github.com/i0natan/nodebestpractices/issues/256)
## ![✔] 7.1. Prefer native JS methods over user-land utils like Lodash
<br/><br/>
## ![✔] 7.1. Don't block the event loop
**TL;DR:** Avoid CPU intensive tasks as they will block the mostly single-threaded Event Loop and offload those to a dedicated thread, process or even a different technology based on the context.
**Otherwise:** As the Event Loop is blocked, Node.js will be unable to handle other request thus causing delays for concurrent users. **3000 users are waiting for a response, the content is ready to be served, but one single request blocks the server from dispatching the results back**
🔗 [**Read More: Do not block the event loop**](/sections/performance/block-loop.md)
<br /><br /><br />
## ![✔] 7.2. Prefer native JS methods over user-land utils like Lodash
**TL;DR:** It's often more penalising to use utility libraries like `lodash` and `underscore` over native methods as it leads to unneeded dependencies and slower performance.
Bear in mind that with the introduction of the new V8 engine alongside the new ES standards, native methods were improved in such a way that it's now about 50% more performant than utility libraries.
@ -1043,6 +1056,7 @@ All statements above will return false if used with `===`
<br/><br/><br/>
# Milestones
To maintain this guide and keep it up to date, we are constantly updating and improving the guidelines and best practices with the help of the community. You can follow our [milestones](https://github.com/i0natan/nodebestpractices/milestones) and join the working groups if you want to contribute to this project

View File

@ -596,7 +596,7 @@ null == undefined // true
<br/><br/>
##! [✔] 5.6. Используйте все ядра процессора
## ![✔] 5.6. Используйте все ядра процессора
**TL;DR:** В своей базовой форме приложение Node работает на одном ядре ЦП, в то время как все остальные не работают. Ваша обязанность -- копировать процесс Node и использовать все процессоры. Для небольших и средних приложений вы можете использовать Node Cluster или PM2. Для более крупного приложения рассмотрите возможность репликации процесса с использованием некоторого кластера Docker (например, K8S, ECS) или сценариев развертывания, основанных на системе инициализации Linux (например, systemd).
@ -1028,13 +1028,26 @@ null == undefined // true
<p align="right"><a href="#оглавление">К началу</a></p>
# `7. Практики эффективности`
# `7. Черновик: Практики эффективности`
## Наши соавторы работают над этим разделом. [Хотите присоединиться?](Https://github.com/i0natan/nodebestpractices/issues/256)
## ![✔] 7.1. Предпочитайте нативные методы JS, а не пользовательские утилиты типа Lodash
<br/><br/>
**TL;DR:** Часто более утомительно использовать служебные библиотеки, такие как `lodash` и` underscore`, по сравнению с нативными методами, так как это приводит к ненужным зависимостям и снижению производительности.
## ![✔] 7.1. Не блокируйте цикл событий
**TL;DR:** Избегайте ресурсоемких задач, поскольку они будут блокировать однопоточный цикл обработки событий, и выгружайте их в выделенный поток, процесс или даже другую технологию в зависимости от контекста.
**Иначе:** Поскольку цикл обработки событий заблокирован, Node.js не сможет обработать другой запрос, что приведет к задержкам для одновременных пользователей. **3000 пользователей ждут ответа, контент готов к отправке, но один-единственный запрос не позволяет серверу отправить результаты обратно**
🔗 [**Read More: Не блокируйте цикл событий**](/sections/performance/block-loop.russian.md)
<br/><br/><br/>
## ![✔] 7.2. Предпочитайте нативные методы JS, а не пользовательские утилиты типа Lodash
**TL;DR:** Часто более утомительно использовать служебные библиотеки, такие как `lodash` и `underscore`, по сравнению с нативными методами, так как это приводит к ненужным зависимостям и снижению производительности.
Имейте в виду, что с введением нового движка V8 наряду с новыми стандартами ES собственные методы были улучшены таким образом, что теперь он примерно на 50% быстрее, чем служебные библиотеки.
**Иначе:** Вам придется поддерживать менее эффективные проекты, где вы могли бы просто использовать то, что **уже** доступно или иметь дело с еще несколькими строками в обмен на еще несколько файлов.
@ -1043,6 +1056,7 @@ null == undefined // true
<br/><br/><br/>
# Вехи
Чтобы поддерживать это руководство и обновлять его, мы постоянно обновляем и совершенствуем рекомендации и лучшие практики с помощью сообщества. Вы можете следить за нашими [вехами](https://github.com/i0natan/nodebestpractices/milestones) и присоединиться к рабочим группам, если хотите внести свой вклад в этот проект.

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

View File

@ -27,6 +27,8 @@ async function executeAsyncTask () {
}
catch(err) {
logger.error(err);
} finally {
await alwaysExecuteThisFunction();
}
}
```

View File

@ -27,6 +27,8 @@ async function executeAsyncTask () {
}
catch(err) {
logger.error(err);
} finally {
await alwaysExecuteThisFunction();
}
}
```

View File

@ -0,0 +1,50 @@
# Don't block the event loop
<br/><br/>
Node handles the Event Loop mostly on a single thread rotating through multiple queues. Operations with high complexity, large json parsing, applying logic over huge arrays, unsafe regex querieies, and large IO operations are some of the operations that can cause the Event Loop to stall. Avoid this off-loading CPU intensive tasks to a dedicated service (e.g. job server), or breaking long tasks into small steps then using the Worker Pool are some examples of how to avoid blocking the Event Loop.
### Example: blocking the event loop
Let's take a look at an example from [Node Clinic](https://clinicjs.org/documentation/doctor/05-fixing-event-loop-problem).
```
function sleep (ms) {
const future = Date.now() + ms
while (Date.now() < future);
}
server.get('/', function (req, res, next) {
sleep(30)
res.send({})
next()
})
```
And when we benchmark this app, we start to see the latency caused by the long
while loop.
### Run the benchmark
`clinic doctor --on-port 'autocannon localhost:$PORT' -- node slow-event-loop`
### The results
```
─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬───────────┐
│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │
├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼───────────┤
│ Latency │ 270 ms │ 300 ms │ 328 ms │ 331 ms │ 300.56 ms │ 38.55 ms │ 577.05 ms │
└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴───────────┘
┌───────────┬─────────┬─────────┬─────────┬────────┬─────────┬───────┬─────────┐
│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │
├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼───────┼─────────┤
│ Req/Sec │ 31 │ 31 │ 33 │ 34 │ 32.71 │ 1.01 │ 31 │
├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼───────┼─────────┤
```
## Image of the Event Loop
![Event Loop](/assets/images/event-loop.png "Event Loop")
>Here's a good rule of thumb for keeping your Node server speedy: Node is fast when the work associated with each client at any given time is "small".
>[Don't Block the Event Loop (or the Worker Pool) | Node.js](https://nodejs.org/en/docs/guides/dont-block-the-event-loop/)
> Most people fail their first few NodeJS apps merely due to the lack of understanding of the concepts such as the Event Loop, Error handling and asynchrony
[Event Loop Best Practices — NodeJS Event Loop Part 5](https://jsblog.insiderattack.net/event-loop-best-practices-nodejs-event-loop-part-5-e29b2b50bfe2)

View File

@ -0,0 +1,50 @@
# Не блокируйте цикл событий
<br/><br/>
Node обрабатывает цикл событий в основном в одном потоке, вращающемся через несколько очередей. Операции с высокой сложностью, большой анализ json, применение логики к огромным массивам, небезопасные запросы регулярных выражений и большие операции ввода-вывода - вот некоторые из операций, которые могут привести к остановке цикла обработки событий. Передавайте такие нагрузки ресурсоемких задач в выделенную службу (например, сервер заданий) или разбивайте длинные задачи на маленькие шаги, а затем используйте рабочий пул - вот некоторые примеры того, как избежать блокировки цикла обработки событий.
### Example: blocking the event loop
Давайте посмотрим на пример из [Node Clinic](https://clinicjs.org/documentation/doctor/05-fixing-event-loop-problem).
```
function sleep (ms) {
const future = Date.now() + ms
while (Date.now() < future);
}
server.get('/', function (req, res, next) {
sleep(30)
res.send({})
next()
})
```
И когда мы тестируем это приложение, мы начинаем видеть задержку, вызванную длительным
while loop.
### Запуск теста тест
`clinic doctor --on-port 'autocannon localhost:$PORT' -- node slow-event-loop`
### Результаты
```
─────────┬────────┬────────┬────────┬────────┬───────────┬──────────┬───────────┐
│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │
├─────────┼────────┼────────┼────────┼────────┼───────────┼──────────┼───────────┤
│ Latency │ 270 ms │ 300 ms │ 328 ms │ 331 ms │ 300.56 ms │ 38.55 ms │ 577.05 ms │
└─────────┴────────┴────────┴────────┴────────┴───────────┴──────────┴───────────┘
┌───────────┬─────────┬─────────┬─────────┬────────┬─────────┬───────┬─────────┐
│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │
├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼───────┼─────────┤
│ Req/Sec │ 31 │ 31 │ 33 │ 34 │ 32.71 │ 1.01 │ 31 │
├───────────┼─────────┼─────────┼─────────┼────────┼─────────┼───────┼─────────┤
```
## Изображение цикла событий
![Event Loop](/assets/images/event-loop.png "Event Loop")
Вот хорошее эмпирическое правило для поддержания скорости вашего Node-сервера: Node работает быстро, когда работа, связанная с каждым клиентом в любой момент времени, "мала".
>[Don't Block the Event Loop (or the Worker Pool) | Node.js](https://nodejs.org/en/docs/guides/dont-block-the-event-loop/)
> Большинство людей терпят неудачу в своих первых нескольких приложениях NodeJS просто из-за отсутствия понимания таких понятий, как цикл обработки событий, обработка ошибок и асинхронность
[Event Loop Best Practices — NodeJS Event Loop Part 5](https://jsblog.insiderattack.net/event-loop-best-practices-nodejs-event-loop-part-5-e29b2b50bfe2)