Networking and Streams Q&A: Buffering Streams
Transcript from the "Q&A: Buffering Streams" Lesson
>> So I see on the chat, Justin has a question about when and how you would need to explicitly close the stream. So, generally you don't need to do this, although sometimes a stream might have some internal state like file descriptors that it ought to free back to the operating system.
[00:00:21] So usually, you don't have to worry about it, but sometimes you do would be my question, my answer, I guess. And it sort of depends on the implementation details of the stream that you're dealing with. So why don't I just go in and show you how I would do that modification, you can compare with how you've done.
[00:00:54] So in here, instead of truncating the output, I guess we could send an error message. And not call next at all. This, whatever message you like. So that ought to work, let's just double check. And now we can do that curl command again, ETOOBIG, very good. And now if I remove the 0's, or those O's rather, and we get ok, fantastic.
[00:01:33] So now we've got program that parses question.
>> So in your program, does that res.end, does that cause the execution inside that if statement to end for that particular function?
>> So basically, if we never call next, then we're never pulling from the stream to get more data, so the stream isn't gonna even generate more data.
>> Do you still need the else block?
>> Yes, yeah. So this only happens if the size is over the threshold that we've established.
>> Could you, this may be semantical, but could you get rid of the else, and then it would, does res.end just totally exit out of the function like a return or does it end?
>> Res.end is just going to, so we're doing res.end right here, and not calling next, so that this part never fires. So you need to call res.end if you're writing an HTTP server just to tell the client that, okay, you've got all of the data that you're gonna get.
[00:02:48] So end is actually a method on writable streams, and we'll get to that in a little bit.
>> But to your question, you could just put a return keyword after the res.end and get the behavior you're talking about.
>> Like this, you mean?
>> And then if this were written like this.
>> Okay, yeah, this is also valid. Just early return versus else, yep. Everything is valid [LAUGH], okay.