Where and how does libUV interact with code on node.js

212 Views Asked by At

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 = true
    • readable._stateReadable.destroyed = true
  • in function _destroy are set states for streams into values:
    • writable._stateWritable.closed = true
    • readable._stateReadable.closed = true
  • in funtion emitCloseNT:
    • sets value writable._stateWritable.closeEmmited = true
    • sets value readable._stateReadable.closeEmmited = true
    • emmits event close

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?

1

There are 1 best solutions below

2
Heiko Theißen On

I'm not a subject matter expert, but after debugging the following code, I got a rough idea of what happens behind the scenes:

var cnt = 0;
new stream.Readable({
  read(size) {
    if (++cnt > 10) this.destroy();
    this.push(String(cnt));
  }
}).pipe(process.stdout);

Upon this.destroy(), the readableState.destroyed is set to true here, and because of this the following this.push("11") returns false here. If readableState.destroyed had been false, it would instead have called addChunk, which would have ensured that reading goes on by emitting a readable event and calling maybeReadMore (see here).

If the readable stream was created by fs.createReadStream, then the _destroy method additionally calls a close method, which closes the file descriptor.