Node.js
Custom stream
Learn to write your own stream class.
What is a custom stream?
In Node.js a custom stream is one you build by extending the built-in Readable, Writable or Transform classes. You customize the flow by implementing _read, _write or _transform methods.
A customStream(name) function models this skeleton: it returns an object with {name, _read, _write}. _read and _write are empty functions; in a real custom stream you fill them in. This lesson builds the skeleton; later you will extend the real Readable class. The new Readable({ read() {} }) option sets up a similar skeleton; here we start with a plain object.
The _read and _write skeleton
A custom stream's skeleton holds the _read and _write methods. _read produces data, _write consumes it. The customStream(name) function returns these two methods as empty functions; in a real custom stream you fill them in.
Example: const stream = customStream('myStream') returns {name: 'myStream', _read: function() {}, _write: function() {}}. typeof stream._read returns 'function'. This skeleton shows the structure of a custom stream; later you build it as a class with class MyStream extends Readable { _read() {} }. Starting with a plain object clarifies the method roles before stepping up to class syntax.
Exercise Write the custom stream skeleton
Write function customStream(name). Return { name: name, _read: function() {}, _write: function() {} }. Define const stream = customStream('myStream'). Print console.log(stream.name), console.log(typeof stream._read) and console.log(typeof stream._write).
Show example solution
function customStream(name) {
return { name: name, _read: function() {}, _write: function() {} };
}
const stream = customStream('myStream');
console.log(stream.name);
console.log(typeof stream._read);
console.log(typeof stream._write);
Test yourself
-
Which method does a custom Readable stream implement?
class MyReadable extends Readable {
_read() {}
}
Show answer
_read — The Readable class implements _read.
-
Match each piece to its role
- Readable
- Produces data
- Writable
- Writes data
- Transform
- Transforms
- _read
- Production method
-
Complete the object property
return { name: name, ____: function() {}, _write: function() {} };
Show answer
return { name: name, _read: function() {}, _write: function() {} };
Next lesson: Summary - Stream internals