In node.js streams come up often, even with the most simple of examples will typically involve logging something to the standard output which is a kind of stream. In this post I will be writing about the fs.createWriteStream method in the node.js built in file system module, and why that is often a better choice for writing to a file compared to other options in that module.
The fs.createWriteStream is an example of a writable stream, which differs from readable streams, and duplex streams. For example when it comes to piping data from one stream to another a readable stream can pipe to a writable stream, but not the other way around, because there is nothing to read. Some of the base events are different as well, if you want to learn more about streams there is always the node.js docs on streams, my content on them as of this writing is a little thin.
So for starters I put together some simple examples of fs.createWriteStream. In these examples I will be just should some very basic use case examples, and will not be getting into anything to intense involving piping, and events.
A simple hello world example of fs.createWriteStream might involve just grabbing a reference to the file system module. Then use the fs.createWriteStream by calling it and passing the path to where the data should be saved as the first argument. Once that is done the write method can be used to write a string to the file.
With writable streams such as the streams created with fs.createWriteStream, data can be piped from a readable stream.
It is possible to attach events to an instance of fs.createWriteStream, or any stream for that matter. The type of events are the stream as with any writable stream, however there are also a few that are for fs.createWriteStream only. In this section I will be going over some of these events,a dn give simple examples.
The error event will fire if an error occurs, for example if I try to write to a file that all ready exists when set in the w+ file mode using the flag option.
A must have event for error handling.
The open event will fire once a file is open, and ready to write to. The first element is the file descriptor of the file.
The pipe event will fire whenever something is being piped in from a readable stream
The fs.createWriteStream method is one of many examples of a writeable stream in node.js. For the most part streams are something that I consume, and there is no need to make my own custom streams. If for some reason you want to do that, you will want to use stream.Writable. If what needs to happen involves streaming data to a file, on the local system though there is not much need to create a custom stream from the ground up though, in most cases fs.createWritweStream will work just fine.