I'm learning about node.js streams at the moment and therefore I'd like to write my own custom streaming module. Here is what I have at the moment:
index.js:
fs = require("fs")
var module = require("./module")
var ws = fs.createWriteStream("out.txt")
fs.createReadStream("in.txt")
.pipe(module())
.pipe(ws)
module.js:
var Stream = require('stream').Stream;
module.exports = function() {
var stream = new Stream();
this.writable = true;
this.readable = true;
stream.write = function(data) {
console.log("write")
stream.emit("data", data)
}
stream.end = function() {
console.log("end")
stream.emit("end")
}
stream.destroy = function() {
console.log("destroy")
stream.emit("close")
}
return stream;
}
in.txt:
text
text
text
text
text
text
text
text
text
text
The problem is that the out.txt
is empty and the stream.write
function is never called. Why is that so? If I comment out my middle pipe is all works fine!
There is one bug in your code which can be easily fixed.
In module.js
change:
this.writable = true;
this.readable = true;
to:
stream.writable = true;
stream.readable = true;
and it will work.
Also if you want to learn more about how to use streams, substack created a nice resource in form of a stream handbook.