0
我需要創建一個讀取文檔的程序,對其進行加密並將結果寫入另一個文檔。所有這些都應該使用變換流完成。 Here's我的代碼:無法實現轉換流
"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");
});
當我運行這個程序,控制檯顯示我說:
TextInfo
a0b5dfe30f8028ab86b1bb48b8f42ebb
Done reading the file
Done writing the file
這意味着,它首先讀取和寫入文檔,但結果是不加密的(「TextInfo 「) - 而應該看起來像這樣」a0b5dfe30f8028ab86b1bb48b8f42ebb「。我確定轉換流邏輯中存在一個錯誤。
任何幫助將不勝感激!
'output.write(tr._transform(' –
@AikonMogwai你的意思是我需要通過tr._transform(數據, 「UTF8」,TR? makeHash)作爲output.write的參數?在這種情況下,程序不起作用,TypeError:無法讀取未定義的屬性'length' –