无法实现Transform流

时间:2017-08-02 12:04:59

标签: node.js stream

我需要创建一个程序来读取doc,加密它并将结果写入另一个doc。所有这些都应该使用变换流来完成。这是我的代码:

"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 个答案:

答案 0 :(得分:1)

我的错误#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}`);
});