Skip to content

Commit 324339c

Browse files
unstooalexandrtovmach
authored andcommitted
RU: blocking vs non-blocking guide (#2337)
* RU: blocking vs non-blocking * translation patch #1 * corresponding translation of guides/index.md
1 parent 24edaac commit 324339c

File tree

2 files changed

+75
-75
lines changed

2 files changed

+75
-75
lines changed
Lines changed: 69 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,53 @@
11
---
2-
title: Overview of Blocking vs Non-Blocking
2+
title: Блокирующие и Неблокирующие Вызовы
33
layout: docs.hbs
44
---
55

6-
# Overview of Blocking vs Non-Blocking
6+
# Обзор Блокирующих и Неблокирующих Вызовов
77

8-
This overview covers the difference between **blocking** and **non-blocking**
9-
calls in Node.js. This overview will refer to the event loop and libuv but no
10-
prior knowledge of those topics is required. Readers are assumed to have a
11-
basic understanding of the JavaScript language and Node.js callback pattern.
8+
Этот обзор рассматривает разницу между **блокирующими** и **неблокирующими**
9+
вызовами в Node.js. Он ссылается на цикл событий (event loop) и библиотеку libuv,
10+
однако предварительное знание этих тем не требуется. Предпологается, что
11+
читатели имеют базовое понимание JavaScript и паттерна обратных вызовов (callback)
12+
в Node.js.
1213

13-
> "I/O" refers primarily to interaction with the system's disk and
14-
> network supported by [libuv](http://libuv.org/).
14+
> Обозначение "I/O" (Ввод/Вывод) в первую очередь ссылается на взаимодействие
15+
> с системным диском и сетью при поддержке [libuv](http://libuv.org/).
1516
1617

17-
## Blocking
18+
## Блокирование
1819

19-
**Blocking** is when the execution of additional JavaScript in the Node.js
20-
process must wait until a non-JavaScript operation completes. This happens
21-
because the event loop is unable to continue running JavaScript while a
22-
**blocking** operation is occurring.
20+
О **блокировании** говорят, когда выполнение JS кода в Node.js
21+
приостановленно до тех пор, пока не завершится работа сторонней операции (например, чтение
22+
какого-нибудь файла). Так происходит, потому что цикл событий не может продолжить исполнение JavaScript,
23+
так как работает **блокирующая** операция.
2324

24-
In Node.js, JavaScript that exhibits poor performance due to being CPU intensive
25-
rather than waiting on a non-JavaScript operation, such as I/O, isn't typically
26-
referred to as **blocking**. Synchronous methods in the Node.js standard library
27-
that use libuv are the most commonly used **blocking** operations. Native
28-
modules may also have **blocking** methods.
25+
В Node.js медленно исполняемый JS код не принято называть **блокирующим**,
26+
если причиной тому высокая нагрузка кода на процессор, а не ожидание завершения
27+
сторонней операции. Синхронные методы в стандартной библиотеке Node.js,
28+
которые используют libuv, наиболее часто применяемые **блокирующие** операции.
29+
Нативные модули также могут иметь **блокирующие** методы.
2930

30-
All of the I/O methods in the Node.js standard library provide asynchronous
31-
versions, which are **non-blocking**, and accept callback functions. Some
32-
methods also have **blocking** counterparts, which have names that end with
33-
`Sync`.
31+
Все I/O методы в стандартной библиотеке Node.js предоставляют свои асинхронные версии,
32+
которые являются **неблокирующими** и принимают функции обратного вызова
33+
в качестве аргумента. Некоторые методы также имеют свои **блокирующие** аналоги.
34+
Названия таких методов закнчиваются на `Sync`.
3435

3536

36-
## Comparing Code
37+
## Сравнение Кода
3738

38-
**Blocking** methods execute **synchronously** and **non-blocking** methods
39-
execute **asynchronously**.
39+
**Блокирующие** методы исполняются **синхронно**, а **неблокирующие** методы
40+
исполняются **асинхронно**.
4041

41-
Using the File System module as an example, this is a **synchronous** file read:
42+
Возьмем модуль File System для примера. Вот пример **синхронного** чтения файла:
4243

4344
```js
4445
const fs = require('fs');
45-
const data = fs.readFileSync('/file.md'); // blocks here until file is read
46+
// исполнение кода заблокированно, пока файл не будет полностью считан
47+
const data = fs.readFileSync('/file.md');
4648
```
4749

48-
And here is an equivalent **asynchronous** example:
50+
А вот эквивалентный **асинхронный** пример:
4951

5052
```js
5153
const fs = require('fs');
@@ -54,63 +56,62 @@ fs.readFile('/file.md', (err, data) => {
5456
});
5557
```
5658

57-
The first example appears simpler than the second but has the disadvantage of
58-
the second line **blocking** the execution of any additional JavaScript until
59-
the entire file is read. Note that in the synchronous version if an error is
60-
thrown it will need to be caught or the process will crash. In the asynchronous
61-
version, it is up to the author to decide whether an error should throw as
62-
shown.
59+
Первый пример выглядит проще чем второй, но он имеет один недостаток: вторая строка
60+
**блокирует** исполнение любого нижеследующего кода, до тех пор, пока
61+
весь file.md не будет считан. Обратите внимание, если синхронная версия кода сгенерирует
62+
исключение, его нужно обработать, иначе процесс Node.js "упадёт". В асинхронном варианте
63+
выбор сгенерировать исключение или нет оставлено на усмотрение программиста.
6364

64-
Let's expand our example a little bit:
65+
Давайте немного расширим наш пример:
6566

6667
```js
6768
const fs = require('fs');
68-
const data = fs.readFileSync('/file.md'); // blocks here until file is read
69+
// исполнение кода заблокированно, пока файл не будет полностью считан
70+
const data = fs.readFileSync('/file.md');
6971
console.log(data);
70-
moreWork(); // will run after console.log
72+
moreWork(); // функция будет исполнена, после console.log
7173
```
7274

73-
And here is a similar, but not equivalent asynchronous example:
75+
А вот похожий, но не эквивалентный асинхронный пример:
7476

7577
```js
7678
const fs = require('fs');
7779
fs.readFile('/file.md', (err, data) => {
7880
if (err) throw err;
7981
console.log(data);
8082
});
81-
moreWork(); // will run before console.log
83+
moreWork(); // функция будет исполнена до console.log
8284
```
8385

84-
In the first example above, `console.log` will be called before `moreWork()`. In
85-
the second example `fs.readFile()` is **non-blocking** so JavaScript execution
86-
can continue and `moreWork()` will be called first. The ability to run
87-
`moreWork()` without waiting for the file read to complete is a key design
88-
choice that allows for higher throughput.
86+
В первом примере метод `console.log` будет вызван до срабатывания функции `moreWork()`.
87+
Во втором примере метод `fs.readFile()` является **неблокирующим**, поэтому исполнение
88+
JavaScript может продолжаться, не дожидаясь окончания его работы. Как следствие
89+
функция `moreWork()` сработает раньше `console.log`. Эта возможность — отсутствие необходимости
90+
дожидаться окончания чтения файла и других системных вызовов — ключевое
91+
инженерное решение, которое обеспечивает высокую пропускную способность Node.js.
8992

9093

91-
## Concurrency and Throughput
94+
## Конкурентность и Пропускная Способность
9295

93-
JavaScript execution in Node.js is single threaded, so concurrency refers to the
94-
event loop's capacity to execute JavaScript callback functions after completing
95-
other work. Any code that is expected to run in a concurrent manner must allow
96-
the event loop to continue running as non-JavaScript operations, like I/O, are
97-
occurring.
96+
Исполнение JavaScript в Node.js является однопоточным. Поэтому, говоря о конкурентности
97+
(параллельности вычислений) в Node.js, подразумевают, что после того, как цикл событий обработал синхронный код,
98+
он способен обработать функции обратного вызова. Подобно сторонним операциям (таким как I/O),
99+
любой конкурентный код должен позволять циклу событий продолжать свою работу.
98100

99-
As an example, let's consider a case where each request to a web server takes
100-
50ms to complete and 45ms of that 50ms is database I/O that can be done
101-
asynchronously. Choosing **non-blocking** asynchronous operations frees up that
102-
45ms per request to handle other requests. This is a significant difference in
103-
capacity just by choosing to use **non-blocking** methods instead of
104-
**blocking** methods.
101+
В качестве примера возьмем запросы к веб-серверу. Допустим, обработка сервером одного запроса
102+
занимает 50мс. Из этих 50мс, 45мс уходит на операции чтения/записи в базу данных.
103+
С базой данных можно взаимодействовать и **асинхронно**. При таком подходе, на каждый запрос
104+
к веб-серверу **неблокирующая** асинхронная операция высвободит 45мс для обработки других
105+
запросов, а это существенная разница.
105106

106-
The event loop is different than models in many other languages where additional
107-
threads may be created to handle concurrent work.
107+
Обработка конкурентной (параллельной) работы при помощи цикла событий в Node.js
108+
отличается от подходов во многих других языках программрования, в которых могут
109+
создаваться дополнительные потоки.
108110

109111

110-
## Dangers of Mixing Blocking and Non-Blocking Code
112+
## Опасность смешивания Блокирующего и Неблокирующего Кода
111113

112-
There are some patterns that should be avoided when dealing with I/O. Let's look
113-
at an example:
114+
Существуют паттерны, которые следует избегать при работе с I/O. Взглянем на пример:
114115

115116
```js
116117
const fs = require('fs');
@@ -121,10 +122,9 @@ fs.readFile('/file.md', (err, data) => {
121122
fs.unlinkSync('/file.md');
122123
```
123124

124-
In the above example, `fs.unlinkSync()` is likely to be run before
125-
`fs.readFile()`, which would delete `file.md` before it is actually read. A
126-
better way to write this, which is completely **non-blocking** and guaranteed to
127-
execute in the correct order is:
125+
В вышеукзанном примере метод `fs.unlinkSync()`, с высокой вероятностью, будет исполнен до
126+
`fs.readFile()`. Это приведет к удалению файла до его прочтения. Лучше переписать
127+
этот код в **неблокирующем** виде, что гарантирует правильный порядок исполнения методов:
128128

129129

130130
```js
@@ -138,11 +138,11 @@ fs.readFile('/file.md', (readFileErr, data) => {
138138
});
139139
```
140140

141-
The above places a **non-blocking** call to `fs.unlink()` within the callback of
142-
`fs.readFile()` which guarantees the correct order of operations.
141+
В последнем примере **неблокирующий** вызов метода `fs.unlink()` расположен внутри функции обратного вызова
142+
`fs.readFile()`. Такой подход гарантирует парвильную последовательность операций.
143143

144144

145-
## Additional Resources
145+
## Дополнительные рессурсы
146146

147147
- [libuv](http://libuv.org/)
148-
- [About Node.js](https://nodejs.org/en/about/)
148+
- [О Node.js](https://nodejs.org/en/about/)

locale/ru/docs/guides/index.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
---
2-
title: Guides
2+
title: Руководства
33
layout: docs.hbs
44
---
55

6-
# Guides
6+
# Руководства
77

8-
## General
8+
## Общее
99

10-
- [Getting Started Guide](getting-started-guide/)
10+
- [Первые шаги](getting-started-guide/)
1111
- [Debugging - Getting Started](debugging-getting-started/)
1212
- [Easy profiling for Node.js Applications](simple-profiling/)
1313
- [Diagnostics - Flame Graphs](diagnostics-flamegraph/)
1414
- [Dockerizing a Node.js web app](nodejs-docker-webapp/)
1515
- [Migrating to safe Buffer constructors](buffer-constructor-deprecation/)
1616

1717

18-
## Node.js core concepts
18+
## Ключевые концепции Node.js
1919

20-
- [Overview of Blocking vs Non-Blocking](blocking-vs-non-blocking/)
20+
- [Блокирующие и Неблокирующие Вызовы](blocking-vs-non-blocking/)
2121
- [The Node.js Event Loop, Timers, and `process.nextTick()`](event-loop-timers-and-nexttick/)
2222
- [Don't Block the Event Loop (or the Worker Pool)](dont-block-the-event-loop/)
2323
- [Timers in Node.js](timers-in-node/)

0 commit comments

Comments
 (0)