Networking and Streams

Writable Streams

Networking and Streams

Check out a free preview of the full Networking and Streams course

The "Writable Streams" Lesson is part of the full, Networking and Streams course featured in this preview video. Here's what you'd learn in this lesson:

After examining the methods for creating writable streams, James demonstrates how to build one.

Preview
Close

Transcript from the "Writable Streams" Lesson

[00:00:00]
>> For writable streams, we have some methods. We've got things like .write, which we've seen. There's also .end, and this is how you put data into the writable stream. You can give end a buffer if you like, and that's basically shorthand for doing a write with that buffer and then calling an int immediately, just a nice little convenience.

[00:00:25]
Writable streams emit a finish event when they're done writing data. So that's important to know about as well. So let's go ahead and make a quick little writable stream here to just test things out. So we'll call it w.js, and we use fs.createWriteStream. So fs.createWriteStream('cool.txt'). And then we'll just w.write('hi\n'), w.write('wow\n'), w.end().

[00:00:59]
That's just an example for what a writable stream looks like. And maybe we'll also listen for the finish event. Just so I can prove to you that there's a finish event. You only get one finish event. So there's a method on the Node.js event emitter API called once that will only listen for one of them.

[00:01:19]
There should only ever be a single event, so either on or once is fine. So I'll just print out FINISHED. Sometimes you might not wanna do something until a writable stream has actually finished writing the results. So a good example of that is if you're writing out to a log file or an important, if you're writing some JSON to a file, then you wanna make sure that you've actually written everything until you do the next step.

[00:01:47]
Because maybe the next step is just gonna read that file. And again, you're not really guaranteed immediately after you end writable stream that it's gonna be finished yet. Because there could be other stuff happening, at the operating system level, and all kinds of levels. So far in this program now, we get the event finished, and there should be a new file called cool.txt that has the output.

[00:02:16]
So we'll add that to the git.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now