Node.js/stream/Readable:修订间差异
来自康健生活
| (未显示同一用户的7个中间版本) | |||
| 第1行: | 第1行: | ||
== 可读流:[http://nodejs.cn/s/9JUnJ8 Readable] == | == 可读流:[http://nodejs.cn/s/9JUnJ8 Readable] == | ||
=== 事件 === | Readable继承EventEmitter。 | ||
==== Data ==== | |||
Readable对应于Java中的InputStream和Reader两个类,针对Readable设置encode编码可完成内部数据由Buffer到字符的转换。Readable Stream有两种模式,即flowing和paused模式。这两种模式对于用户而言区别在于是否需要手动调用<code>Readable.prototype.read(n)</code>,读取缓冲区的数据。对于Readable实例而言,_read函数用于准备从源文件中获取数据并添加到读缓冲中。 | |||
查询node API文档可知触发flowing模式有三种方式: | |||
* 侦听data事件 | |||
* readable.resume() | |||
* readable.pipe() | |||
而触发paused模式同样有几种方式: | |||
* 移除data事件 | |||
* readable.pause() | |||
* 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类型的对象,保存了Readable实例的重要信息,如读取模式(是否为对象模式)、highWaterMark(缓冲区存放的最大字节数)、缓冲区、flowing模式等。在Readable的实现中,处处使用ReadableState对象记录当前读取状态,并设置缓冲区保证读操作的顺利进行。 | |||
== 事件 == | |||
{| class="wikitable" | |||
|- | |||
| data || 示例 || 示例 | |||
|- | |||
| end || 示例 || 示例 | |||
|- | |||
| error || 示例 || 示例 | |||
|- | |||
| close || 示例 || 示例 | |||
|- | |||
| readable || 示例 || 示例 | |||
|} | |||
== 函数 == | |||
{| class="wikitable" | |||
|- | |||
| pipe(),unpipe() || 示例 || 示例 | |||
|- | |||
| read(),unshift(),resume() || 示例 || 示例 | |||
|- | |||
| pause(),isPaused() || 示例 || 示例 | |||
|- | |||
| setEncoding() || 示例 || 示例 | |||
|} | |||
== Data == | |||
== 模式 == | |||
可读流有流动和暂停两种模式,可读流能够流动起来的驱动力在其resume方法,如: | |||
<syntaxhighlight lang="javascript"> | |||
//伪代码 | |||
function flow(stream){ | |||
const state=stream._readableState; | |||
state.flowing=true; | |||
while(state.flowing && stream.read() !== null); | |||
} | |||
Readable.prototype.resume=function(){ | |||
//... | |||
flow(this); | |||
//... | |||
} | |||
//伪代码 | |||
function fromList(n,state){ | |||
var ret; | |||
ret= /*从缓存池state.buffe中取数据*/ | |||
return ret; | |||
} | |||
Readable.prototype.read=function(n){ | |||
var state=this._readableState; | |||
//... | |||
this._read(state.highWaterMark); | |||
//... | |||
var ret=fromList(n,state); | |||
if(ret===null){ | |||
//... | |||
}else{ | |||
//标记消耗量 | |||
state.length-=n; | |||
} | |||
//触发事件,发送数据 | |||
if(ret !==null) this.emit('data',ret); | |||
return data; | |||
};</syntaxhighlight> | |||
=== Readable === | === Readable === | ||
什么时机会从文件读取数据到可读流内部缓存中? | 什么时机会从文件读取数据到可读流内部缓存中? | ||
| 第195行: | 第317行: | ||
|- | |- | ||
| flags|| 对文件进行何种操作 || 'r' | | flags|| 对文件进行何种操作 || 'r' | ||
|- | |||
| mode|| 8进制,d rwx r-x r-x 第一个d代表文件夹,后三位代表自己,中间代表组成员,最后代表访客。 | |||
//2读4写1执行。2+4就是6代表能写能读 777就是最大权限。也可以写十进制438 || 0o666 | |||
|- | |||
| autoClose|| 是否自动关闭 || true | |||
|- | |- | ||
| encoding || 设置之后,读取的是字符串,不然默认为buffer || 'utf-8' | | encoding || 设置之后,读取的是字符串,不然默认为buffer || 'utf-8' | ||
| 第211行: | 第338行: | ||
let rs = fs.createReadStream('示例文本.txt', { | let rs = fs.createReadStream('示例文本.txt', { | ||
// 配置项 | // 配置项 | ||
}) | }); | ||
//内部发布订阅模式 | |||
//默认是暂停模式 | |||
//监听data会改为流动模式 | |||
let arr = []; | let arr = []; | ||
rs.on('open',function (fd) { | |||
console.log('open',fd); | |||
}) | |||
rs.on('data',function(chunk){ | rs.on('data',function(chunk){ | ||
arr.push(chunk); // 将 buffer 类型的数据流推送到数组中 | arr.push(chunk); // 将 buffer 类型的数据流推送到数组中 | ||
}) | }) | ||
// 内部emit的data | |||
rs.end('end',function(){ | rs.end('end',function(){ | ||
let newFileData = Buffer.concat(arr).toString() | let newFileData = Buffer.concat(arr).toString() | ||
| 第222行: | 第356行: | ||
// error | // error | ||
})</syntaxhighlight> | })</syntaxhighlight> | ||
* 另外 rs.pause()可以把流动模式改为暂停模式,恢复使用rs.resume() | |||
=== 慢客户端 === | === 慢客户端 === | ||
在 Node 进行 I/O 操作时不会产生阻塞,也就是说 Node 不会阻塞数据的读写操作,如果写操作无法将数据写入核缓冲区,就会缓存数据,如果是客户端->服务器网络连接,受限于网速,可读流很快,可写流会很慢,核缓冲区将被爆满。 | 在 Node 进行 I/O 操作时不会产生阻塞,也就是说 Node 不会阻塞数据的读写操作,如果写操作无法将数据写入核缓冲区,就会缓存数据,如果是客户端->服务器网络连接,受限于网速,可读流很快,可写流会很慢,核缓冲区将被爆满。 | ||
在写进流的过程中,node并不一定能够及时的将数据写入kernel buffer,这个时候Node就会 | |||
将数据保存在缓冲队列中,在适当的时候才会重新将数据写入到正确的位置,这个时候可能需要监听一些事件来知道 | |||
何时那些缓冲队列的数据被重新写入了,该事件就是drain. | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
rs.on('data',function(chunk){ | rs.on('data',function(chunk){ | ||