Book Image

Node Cookbook: Second Edition

By : David Mark Clements
Book Image

Node Cookbook: Second Edition

By: David Mark Clements

Overview of this book

Table of Contents (18 chapters)
Node Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Making stream interfaces


The Consuming streams and Playing with pipes recipes show us how to initiate and interact with various stream interfaces, such as the fs module's read and write streams, the http module's response object's write stream, and third-party modules, such as JSONStream (refer to the There's More… section of Playing with pipes).

In this recipe, we're going to make our own basic read and write stream interfaces.

Getting ready

Let's create and open a file, which we'll name basic_streams.js.

How to do it…

Node's stream module contains some base constructors to create streams. So, let's require the stream module and instantiate a readable stream as well as a writable stream:

var stream = require('stream'); 
var writable = new stream.Writable(); 
var readable = new stream.Readable(); 
var store = [];

We've also created an empty array named store. We'll be writing to store via the writable stream and reading from it with the readable stream.

To create streams that we intend to reuse...