I need to create a program that reads doc, encrypts it and writes the result to another doc. All of that should be done using transform stream. Here´s my code:
"use strict";
const fs = require("fs");
const crypto = require("crypto");
const Transform = require("stream").Transform;
// Make read and write streams
const input = fs.createReadStream("./logs/data.txt");
let output = fs.createWriteStream("./logs/newdata.txt");
// 2 functions that encrypt data and transform it
class CT extends Transform {
constructor() {
super();
}
// Encryption function
makeHash(err, data) {
if (err) throw err;
return crypto.createHash("md5").update(data).digest("hex")
}
// Encryption function will be passed as a callback
_transform(data, encoding, callback) {
callback(null, data);
}
}
let data;
// Make transform stream
let tr = new CT;
input.on("readable", () => {
while (data = input.read()) {
tr._transform(data, "utf8", tr.makeHash);
console.log(data.toString());
console.log(tr.makeHash(null, data));
output.write(data, "utf8", () => {
output.end();
console.log("Done writing the file");
});
}
});
input.on("error", (err) => {
console.error(`Unexpected ${err}`);
});
input.on("end", () => {
console.log("Done reading the file");
});
When I run this program, console shows me that:
TextInfo
a0b5dfe30f8028ab86b1bb48b8f42ebb
Done reading the file
Done writing the file
It means that it initially reads and writes docs, but the result is not encrypted ("TextInfo") - instead it should look like this "a0b5dfe30f8028ab86b1bb48b8f42ebb". I´m sure there´s a mistake in transform stream logic.
Any help will be appreciated!
output.write(tr._transform(,?