我需要创建一个程序来读取文档,对其进行加密,然后将结果写入另一个文档。所有这些都应该使用转换流来完成。这是我的代码:

"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”。我确定转换流逻辑中有一个错误。

任何帮助将不胜感激!

最佳答案

我的错误#1是我创建了一个读取流-相反,我应该只声明读取文件的变量输入,并且在回调函数中擅长使用转换流来写入其内容。

错误#2是我错误地实现了功能makeHash:现在,它完美地加密并写入了文件。因此,此函数称为_transform函数的回调。

这是工作代码:

"use strict";
const fs = require("fs");
const crypto = require("crypto");
const Transform = require("stream").Transform;

const input = fs.readFile("./logs/data.txt", "utf8", (err, content) => {
  if (err) throw err;
  tr.write(content);
});
let output = fs.createWriteStream("./logs/newdata.txt");

class CT extends Transform {
  constructor() {
    super();
  }
  // Function declares cData - encrypted input text and writes it to the file
  makeHash(err, data) {
    let cData = crypto.createHash("md5").update(data).digest("hex");
    output.write(cData, "utf8", () => {
      output.end();
      console.log("Done writing the file");
    });
  }

  _transform(chunk, encoding, callback) {
    callback(null, chunk);
  }
}

let tr = new CT;
tr.on("data", (chunk) => tr._transform(chunk, "utf8", tr.makeHash));

tr.on("error", (err) => {
  console.error(`Unexpected ${err}`);
});

09-25 19:00