Custom stream
- Node.js course
- Expert
- Lesson 29/47
- 5 min
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.
Practice 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).
Starter code
// Write the customStream function
// Return an object with {name, _read, _write}
// Call with myStream, print name and method types
// write hereSample 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);Expected output
myStream function function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method does a custom Readable stream implement?
class MyReadable extends Readable {
_read() {}
}- _close
- _read Correct answer
- _open
- _start
Explanation: The Readable class implements _read.
2 Match each piece to its role
| Term | Meaning |
|---|---|
Readable |
Produces data |
Writable |
Writes data |
Transform |
Transforms |
_read |
Production method |
3 Complete the object property
return { name: name, ____: function() {}, _write: function() {} };
return { name: name, _read: function() {}, _write: function() {} };
Explanation: _read is the production method.