Node.js/stream/Readable:修订间差异
来自康健生活
| (未显示同一用户的10个中间版本) | |||
| 第1行: | 第1行: | ||
== 可读流:[http://nodejs.cn/s/9JUnJ8 Readable] == | == 可读流:[http://nodejs.cn/s/9JUnJ8 Readable] == | ||
Readable继承EventEmitter。 | |||
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 === | |||
什么时机会从文件读取数据到可读流内部缓存中? | |||
# 开始执行时,可读流内部缓存中没有数据,会先读取highWaterMark(默认64kb,可指定)个字节的数据到内部缓存中。 | |||
# readable读取之后,如果内部缓存区中的字节少于highWaterMark个字节的时候,会主动再读取highWaterMark字节的数据到内部缓存中。 | |||
# 如果readable读取后,内部缓存中没有数据了,会主动再读取highWaterMark字节的数据到内部缓存中。这是2中的一种特殊情形。 | |||
# 当readable触发时,如果缓存中的数据不够读取,则会读取最邻近的2的高次幂个字节放入缓存中。例如本次readable要读取5个字节,但是缓存中字节小于5个,则会读取2^3个字节到缓存中。 | |||
什么时候会调用readable将内部缓存中的数据取出? | |||
# 当可读流内部缓存区中字节数为0的时候,包括开始执行时的0和后期读取时被清空两种情形,会触发一次readable事件。 | |||
# 如果readable执行时,当前缓存区中的数据不够读取,则会在从文件读取数据到缓存(对应读取文件时机的第4条)后,再次触发readable事件。 | |||
# 当到达可读流底部的时候,也就是文件已经被全部读到缓存中,且调用过一次readable事件后,会再次触发readable事件。(这是一次校验清理缓存的过程,也是上面例子最后输出了null的原因) | |||
模拟实现 | |||
<syntaxhighlight lang="javascript"> | |||
let fs = require('fs'); | |||
let EventEmmitter = require('events'); | |||
function computeNewHighWaterMark(n) { | |||
n--; | |||
n |= n >>> 1; | |||
n |= n >>> 2; | |||
n |= n >>> 4; | |||
n |= n >>> 8; | |||
n |= n >>> 16; | |||
n++; | |||
return n; | |||
} | |||
class ReadStream extends EventEmmitter { | |||
constructor(path, options) { | |||
super(); | |||
this.path = path; | |||
this.flags = options.flags || 'r'; | |||
this.autoClose = options.autoClose || true; | |||
this.encoding = options.encoding || 'utf8'; | |||
this.highWaterMark = options.highWaterMark || 64 * 1024; | |||
this.start = options.start || 0; | |||
// 当前缓存里内容的字节数 | |||
this.readableLength = 0; | |||
// 缓存区 | |||
this.buffers = []; | |||
// 当需要读取时,先判断是不是正在读取,如果正在读取时,就不要再去读取了 | |||
this.reading = false; | |||
// 是否需要触发readable事件 | |||
this.emittedReadable = false; | |||
// 文件当前要读取的位置 | |||
this.pos = this.start; | |||
// 用于记录文件是否已经读到末尾 | |||
this.fileSize = fs.statSync(path).size; | |||
// 读之前先打开文件,注意是异步的 | |||
this.open(); | |||
// 判断是否监听了readable事件,如果是则开始读取文件,第一次读取highWaterMark个字节 | |||
this.on('newListener', (type) => { | |||
if (type === 'readable') { | |||
this.read(); | |||
} | |||
}) | |||
} | |||
// 这里的read等同于rs.read([size]),n代表要读取的字节数 | |||
read(n) { | |||
if(this.fileSize === this.pos && this.isLast){ | |||
// 如果上一次已经将文件读完了,则直接返回内部缓存区剩余的内容 | |||
return this.buffers.shift(); | |||
} | |||
// 如果要读取的内容长度比缓存区中的长度大,则将highWaterMark置为最近的2的多少次方,重新触发read事件 | |||
if (n > this.readableLength) { | |||
this.highWaterMark = computeNewHighWaterMark(n); | |||
this.emittedReadable = true; | |||
// 保证没有正在读取再进行读取 | |||
if (!this.reading) { | |||
this.reading = true; | |||
this._read(); | |||
} | |||
} | |||
// 如果定义了n,则本次要读取的内容存放在curReadBuf中进行返回,即curReadBuf是读取的结果 | |||
let curReadBuf; | |||
// 如果内部缓存中有则进行取出,放入要返回的curReadBuf中 | |||
if (n > 0 && n <= this.readableLength) { | |||
curReadBuf = Buffer.alloc(n); | |||
let buf; // 用于存储每次循环从内部缓存中取出的数据 | |||
let index = 0; // curReadBuf中当前最大的索引 | |||
let flag = true; // 用于在内部for循环中实现跳出while循环 | |||
// 依次取内部缓存buffers中的数据,给curReadBuf进行赋值 | |||
// buffers中的状态是:[buffer<5,6,7,8>,buffer<9,10,11,12>] | |||
while (flag && (buf = this.buffers.shift())) { | |||
for (let i = 0; i < buf.length; i++) { | |||
curReadBuf[index++] = buf[i]; | |||
if (index === n) { | |||
// 如果数据已经取了n个,则跳出while循环和本次的for循环,同时更新内部缓存区的长度,并将取出的多余数据塞回内部缓存区 | |||
flag = false; | |||
this.readableLength -= n; | |||
// 将剩余没有消耗的在塞回到内部缓存区 | |||
let r = buf.slice(i + 1); | |||
if (r.length) { | |||
this.buffers.unshift(r); | |||
} | |||
break; | |||
} | |||
} | |||
} | |||
} | |||
// 如果缓存区没有内容,需要先去读取内容,然后触发readable事件,这里只是标识可以触发readable事件,没有去读取 | |||
if (this.readableLength === 0) { | |||
this.emittedReadable = true; | |||
} | |||
// 如果缓存区长度小于highWaterMark,且没有正在读取,则需要去读取数据 | |||
if ((this.readableLength < this.highWaterMark) && !this.reading) { | |||
this.reading = true; | |||
this._read(); | |||
} | |||
// 如果本次读取的结果已经是文件底部了允许触发readable | |||
if(this.fileSize === this.pos){ | |||
this.emittedReadable = true | |||
} | |||
return curReadBuf || null; | |||
} | |||
_read() { | |||
// 如果文件还没有打开则等文件打开之后再进行读取 | |||
if (typeof this.fd !== 'number') { | |||
return this.once('open', () => this._read()); | |||
} | |||
// 每次读highWaterMark这么多 | |||
let buffer = Buffer.alloc(this.highWaterMark); | |||
fs.read(this.fd, buffer, 0, buffer.length, this.pos, (err, byteRead) => { | |||
// 读完了重置reading标识 | |||
this.reading = false; | |||
// 如果有读出内容,则进行标识重置及将内容放入内置的缓存区(buffers)中 | |||
if (byteRead > 0) { | |||
// 维护缓存的长度 | |||
this.readableLength += byteRead; | |||
// 重置下次开始读文件的位置 | |||
this.pos += byteRead; | |||
// 将读取到的buffer返给内置的缓存buffers中 | |||
this.buffers.push(buffer.slice(0, byteRead)); | |||
if (this.emittedReadable) { | |||
//默认下一次不触发readable事件 | |||
this.emittedReadable = false; | |||
// 可以读取了,默认缓存满了 | |||
this.emit('readable'); | |||
} | |||
} else { | |||
// 最后一次到达流底部的时候触发readable | |||
this.isLast = true; | |||
if (this.emittedReadable) { | |||
this.emittedReadable = false; | |||
this.emit('readable'); | |||
} | |||
// 当读取不到内容时触发end事件 | |||
this.emit('end'); | |||
} | |||
}); | |||
} | |||
destroy() { | |||
fs.close(this.fd, () => { | |||
this.emit('close'); | |||
}) | |||
} | |||
// 打开要读取的文件 | |||
open() { | |||
fs.open(this.path, this.flags, (err, fd) => { | |||
if (err) { | |||
this.emit('error', err); | |||
if (this.autoClose) { | |||
this.destroy(); | |||
} | |||
return; | |||
} | |||
this.fd = fd; | |||
this.emit('open', this.fd); | |||
}) | |||
} | |||
} | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="javascript"> | |||
let path = require('path'); | |||
let ReadStream = require('./chat'); | |||
let rs = new ReadStream(path.join(__dirname, '1.txt'),{ | |||
highWaterMark: 7 | |||
}); | |||
rs.on('readable', function(data){ | |||
// 每次读取后内部缓存中剩余的字节数 | |||
console.log(rs.readableLength) | |||
console.log(rs.read(8)); | |||
// 每次读取后内部缓存中剩余的字节数 | |||
console.log(rs.readableLength) | |||
</syntaxhighlight> | |||
=== 参数 === | === 参数 === | ||
{| class="wikitable" | {| class="wikitable" | ||
|- | |- | ||
| 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' | ||
| 第20行: | 第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() | ||
| 第32行: | 第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){ | ||
if(!res.write(data)){ | |||
rs.pause(); | |||
} | |||
}); | |||
res.on('drain',functon(){ | |||
}) | rs.resume(); | ||
}); | |||
rs.on('end',function(){ | |||
res.end(); | |||
});</syntaxhighlight> | |||
# 当往可写流里写数据的时候,不会立刻写入文件,先写入缓存区,缓存区的大小就是highWaterMark,默认为16k,等缓存区满了之后,再次真正的写入文件里 | # 当往可写流里写数据的时候,不会立刻写入文件,先写入缓存区,缓存区的大小就是highWaterMark,默认为16k,等缓存区满了之后,再次真正的写入文件里 | ||
# 通过判断ws.write的返回值判断缓存区是否已经满了。为true是,还没满,有空间,可以继续写,为false时,表示满了 | # 通过判断ws.write的返回值判断缓存区是否已经满了。为true是,还没满,有空间,可以继续写,为false时,表示满了 | ||
| 第56行: | 第385行: | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
const fs = require('fs') | const fs = require('fs') | ||
let ws = fs.createWriteStream('示例文本.txt', { | |||
// 配置项 | |||
let ws = fs.createWriteStream(' | |||
}) | }) | ||
var flag = ws.write('1', function(){}) //flag为true | var flag = ws.write('1', function(){}) //flag为true | ||
| 第70行: | 第396行: | ||
// 当数据写入文件后,又有空间继续写入时,触发drain事件 | // 当数据写入文件后,又有空间继续写入时,触发drain事件 | ||
ws.on('drain',function(){ | ws.on('drain',function(){ | ||
// | |||
}) | }) | ||
// 当所有文件写完之后,触发end,也可以在end时,在写入最后的数据 | // 当所有文件写完之后,触发end,也可以在end时,在写入最后的数据 | ||
ws.end('结束写入')</syntaxhighlight> | ws.end('结束写入')</syntaxhighlight> | ||