@@ -265,13 +265,95 @@ readable.setEncoding('utf-8');
265265readable .on (' readable' , () => {
266266 let chunk;
267267 while (null !== (chunk = readable .read (10 ))) {
268- console .log
268+ console .log (` 接收到${ chunk .length } 字节的数据` );
269+ console .log (` 接收到的数据是:${ chunk} ` );
269270 }
270271})
271272
272273readable .on (' end' , () => {
273- console .log ()
274+ console .log (' 结束 ' )
274275})
275276```
276277
278+ 使用 readable.read() 处理数据时,while 循环是必需的。只有在 readable.read() 返回 null 之后,才会发生 readable 事件;readable.setEncoding() 用于设置字符编码。默认情况下没有设置字符编码,流数据返回的是Buffer对象。如果设置了字符编码,则流数据返回指定编码的字符串。
279+
280+ 调用 readable.setEncoding('utf-8')会将数据解析为UTF-8数据,并返回字符串。
281+
282+ 调用 readable.setEncoding('hex')则会将数据编码成 十六进制字符串。
283+
284+ 6 . readable.unpipe([ destination] )
285+
286+ 解绑之前使用stream.pipe()绑定的可写流。
287+
288+ 如果没有指定目标可写流,则解绑所有管道,如果指定了流目标可写流,但它没有建立管道,则不起作用。
289+
290+ ``` js
291+ const fs = require (' fs' );
292+
293+ const readable = fs .createReadStream (' data.txt' );
294+
295+ const writable = fs .createWriteStream (' write-data.txt' );
296+
297+ // readable 的所有数据都推送到 write-data.txt
298+ readable .pipe (writable);
299+
300+ setTimeout (() => {
301+ console .log (' 停止写入数据' );
302+ readable .unpipe (writable);
303+ console .log (' 收到关闭文件流' );
304+ writable .end ();
305+ }, 3 );
306+ ```
307+
308+
309+ ## 异步迭代器
310+
311+ 可读流中提供了异步迭代器的使用
312+
313+ ``` js
314+ const fs = require (' fs' );
315+
316+ async function print (readable ) {
317+ readable .setEncoding (' utf8' );
318+ let data = ' ' ;
319+ // 迭代器
320+ for await (const k of readable ) {
321+ data += k;
322+ }
323+ console .log (data);
324+ }
325+
326+ print (fs .createReadStream (' file' )).catch (console .log );
327+ ```
328+
329+ 如果循环以break 或 throw终止,则流将被销毁。
330+
331+ 迭代流将完全销毁流,并以大小等于 highWaterMark选项的块读取流。
332+
333+ 如果文件的数据少于64kb,则数据将位于单个块中,因为没有为 fs.createReadStream() 提供 highWaterMark 选项。
334+
335+ ## 两种读取模式
336+
337+ 可读流 运作于 流动模式 flowing 或 暂停模式 paused 两种模式之一。
338+
339+ 在流动模式中,数据自动从底层系统读取,并通过 EventEmitter 接口的事件尽可能快地被提供给应用程序。
340+
341+ 在暂停模式中,必须显式调用 stream.read() 读取数据块。
342+
343+ 所有可读流都开始于暂停模式,可以通过以下方式切换到流动模式。
344+
345+ 添加 data 事件句柄
346+
347+ 调用 stream.resume()
348+
349+ 调用 stream.pipe()
350+
351+
352+
353+
354+
355+
356+
357+
358+
277359
0 commit comments