Node.js/stream/Readable:修订间差异
来自康健生活
| 第2行: | 第2行: | ||
Readable继承EventEmitter。 | Readable继承EventEmitter。 | ||
Readable对应于Java中的InputStream和Reader两个类,针对Readable设置encode编码可完成内部数据由Buffer到字符的转换。Readable Stream有两种模式,即flowing和paused模式。这两种模式对于用户而言区别在于是否需要手动调用<code>Readable.prototype.read(n)</code> | Readable对应于Java中的InputStream和Reader两个类,针对Readable设置encode编码可完成内部数据由Buffer到字符的转换。Readable Stream有两种模式,即flowing和paused模式。这两种模式对于用户而言区别在于是否需要手动调用<code>Readable.prototype.read(n)</code>,读取缓冲区的数据。对于Readable实例而言,_read函数用于准备从源文件中获取数据并添加到读缓冲中。 | ||
查询node API文档可知触发flowing模式有三种方式: | 查询node API文档可知触发flowing模式有三种方式: | ||
| 第15行: | 第15行: | ||
* readable.pause() | * readable.pause() | ||
* readable.unpipe() | * readable.unpipe() | ||
== 异步迭代器 == | |||
从可读的流读取数据时,可以使用 async iterator | |||
<syntaxhighlight lang="javascript"> | |||
import * as fs from 'fs'; | |||
async function logChunks(readable) { | |||
for await (const chunk of readable) { | |||
console.log(chunk); | |||
} | |||
} | |||
const readable = fs.createReadStream( | |||
'tmp/test.txt', {encoding: 'utf8'}); | |||
logChunks(readable); | |||
// Output: | |||
// 'This is a test!\n'</syntaxhighlight> | |||
也可以在字符串中收集可读流的内容 | |||
<syntaxhighlight lang="javascript"> | |||
import { Readable } from 'stream'; | |||
async function readableToString2(readable) { | |||
let result = ''; | |||
for await (const chunk of readable) { | |||
result += chunk; | |||
} | |||
return result; | |||
} | |||
const readable = Readable.from('Good morning!', { encoding: 'utf8' }); | |||
assert.equal(await readableToString2(readable), 'Good morning!');</syntaxhighlight> | |||
使用异步函数,因为我们希望返回一个 Promise。 | |||
=== 异步函数与 EventEmitter 区别 === | |||
== 实例属性 == | == 实例属性 == | ||
=== _readableState === | === _readableState === | ||