I wondered a question: "where and how does libUV interact with code on node.js". Lately I was investigating streams, also I read source on github.
Well, let's take source of script called as destroy.js. This script is responding for the destruction of streams: stream.destroy(). After that operation:
- in function destroy are set states for streams into values:
writable._stateWritable.destroyed = truereadable._stateReadable.destroyed = true
- in function _destroy are set states for streams into values:
writable._stateWritable.closed = truereadable._stateReadable.closed = true
- in funtion emitCloseNT:
- sets value
writable._stateWritable.closeEmmited = true - sets value
readable._stateReadable.closeEmmited = true - emmits event
close
- sets value
That's all. Where and how does libUV interact with stream.destroy()? Even documentation of node about writable.destroy says:
This is a destructive and immediate way to destroy a stream
But what is it really? I see only the process of setting state for the streams and only it. So, where does libUV actually destroy stream?
I'm not a subject matter expert, but after debugging the following code, I got a rough idea of what happens behind the scenes:
Upon
this.destroy(), thereadableState.destroyedis set totruehere, and because of this the followingthis.push("11")returnsfalsehere. IfreadableState.destroyedhad beenfalse, it would instead have calledaddChunk, which would have ensured that reading goes on by emitting areadableevent and callingmaybeReadMore(see here).If the readable stream was created by
fs.createReadStream, then the_destroymethod additionally calls aclosemethod, which closes the file descriptor.