I'm having trouble understanding the following code:
const fs = require('fs')
const readableStream = fs.createReadStream(__filename)
readableStream.close()
readableStream.on('close', () => {
console.log('Stream closed')
})
The above code outputs the string 'Stream closed'. I'm confused about why that happens because the event handler for the close event is attached after the call to close(). It looks like the stream actually gets closed after the event handler is attached. How does this code work? What do the close() and on() functions do internally? When does the close event's callback get added to the event queue for the close callbacks phase of the event loop?
I did some reading and also dug through the Node.js source code. I now understand how the close()
and on()
functions work.
First, regarding the close()
function, I had misunderstood that it adds a callback in the queue of the close callbacks phase of the event loop. It doesn't really do that. Actually, the close()
function uses a promise to close the file (see https://github.com/nodejs/node/blob/a273674deed0a28d4eb4d4979e879139b14baa3e/lib/internal/fs/streams.js#L90). In the callback that's executed when the promise resolves, the close event is emitted using process.nextTick()
(see https://github.com/nodejs/node/blob/231548b5cf23a1e7a25d0c323bc5b485e10cbcea/lib/internal/streams/destroy.js#L115).
As for the on()
function, it simply adds a function to the list of handlers associated with a particular event.