-
Notifications
You must be signed in to change notification settings - Fork 472
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Node.js Writable Stream的实现简析 #28
Comments
learning |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Node.js Writable Stream的实现简析
可写流是对数据写入“目的地”的一种抽象,可作为可读流的一种消费者。数据源可能多种多样,如果使用了可写流来完成数据的消费,那么就有可写流的内部机制来控制数据在生产及消费过程中的各状态的扭转等。
首先来看下可写流内部几个比较关键的状态:
在实现的可写流当中必须要定义一个
write
方法,在可写流内部,这个方法会被赋值给一个内部_write
方法,主要是在数据被消费的时候调用:可写流对开发者暴露了一个
write
方法,这个方法用于接收数据源的数据,同时来完成数据向消费者的传递或者是将数据暂存于缓冲区当中。让我们来看下一个简单的例子:
程序开始后,首先可写流调用
writer.write
方法,将数据data
传入到可写流当中,然后可写流内部来判断将数据是直接提供给数据消费者还是暂时先存放到缓冲区。在
doWrite
方法中调用了开发者定义的write
方法来完成数据的消费,即stream._write()
,同时也提到了关于当数据被消费完了后需要调用state.onwrite
这个方法来同步可写流的状态。接下来就来看下这个方法的内部实现:每次调用
onWrite
方法时,首先都会调用onwriteStateUpdate
方法来更新这个可写流的状态,具体见上面的方法定义。同时需要对这个可写流进行判断,是否要关闭这个可写流。同时还进行判断buffer
是否还有可供消费者使用的数据。如果有那么就调用clearBuffer
方法用以将缓冲区的数据提供给消费者来使用。背压
当数据源提供给可写流的数据过快的时候有可能出现背压的情况,这个时候数据源不再提供数据给可写流,是否出现背压的情况,可通过可写流的
write
方法的返回值来进行判断,如果返回的是false
,那么就出现的了背压。参见这个例子在实现的
write
方法中通过setTimeout
来延迟一段时间调用onwrite
方法,这个时候每次数据消费者都拿到了数据,但是因为这个地方延迟了更新可写流的状态,但是从数据源向可写流中还是同步的写入数据,因此可能会出现在可写流的缓冲区保存的数据大于hmw
的情况。在
writeOrBuffer
方法中有关于可写流缓冲区保存的数据长度和hwm
的比较:将
needDrain
置为true
。出现背压后,数据源不再提供数据给可写流,这个时候只有等可写流将缓冲区的所有完成全部提供给消费者消耗,同时更新完可写流的状态后,会触发一个drain
事件。这个时候如果你的程序提前定义的监听
drain
事件的方法,那么可以在回调里面再次调用可写流的write
方法来让数据源继续提供数据给可写流。The text was updated successfully, but these errors were encountered: