I am trying to modify some files using node file streams and custom transform function. This is the transform function:
const TransformStream = function() {
Transform.call(this, {objectMode: true});
};
util.inherits(TransformStream, Transform);
TransformStream.prototype._transform = function(chunk, encoding, callback) {
let line = chunk.toString()
if (!this.findLinesMode && lineStartRe.test(line)) {
this.findLinesMode = true
this.lines = []
}
if (this.findLinesMode) {
this.lines.push(line)
}
if (this.findLinesMode && lineEndRe.test(line)) {
this.findLinesMode = false
line = this.lines.join('').replace(re, (str, match) => match.trim())
}
if (!this.findLinesMode) {
this.push(line + '\n')
}
callback()
};
And I tried to use it in the following code:
byline(fs.createReadStream(filePath, {encoding: 'utf8'}))
.pipe(new TransformStream())
.pipe(fs.createWriteStream(filePath))
However, the file ends up empty.
I am confident that the transformer code works as expected, because I tried pipe it to process.stdout and the output is exactly how I want it.
My question is: What I am doing wrong and what can I try to fix it?