No, the counter won't be out of order. Streams insert items into the outgoing buffer as you call .write()
and all your writes are called in order.
But, a loop like this needs flow control on the writer.write()
because if it returns false
, then you can't write any more until the drain
event on the stream indicates that there is more room for writing. See here in the doc for more info.
The write.write()
function is asynchronous, but because of buffering and other events on the stream you don't necessarily have to register a complete callback for every write. The write.write()
puts data in the outbound buffer and returns true
immediately when the data has been successfully buffered or it returns false
immediately if there's no room in the buffer.
The actual write to the file stream is indeed asynchronous and occurs largely out of your view. Errors from the asynchronous part are communicated via the error
event on the stream and, as you're already doing, completion of the stream is also communicated via an event.
The reason you get Finished Writing
after Hello
is because of the asynchronous writing behind the scenes. Your for
loop sets off the writes, but they are not yet complete when the for
loop is done. They finish some time later (when you see the finish
event).