2017-08-02 82 views
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「。我確定轉換流邏輯中存在一個錯誤。

任何幫助將不勝感激!

+0

'output.write(tr._transform(' –

+0

@AikonMogwai你的意思是我需要通過tr._transform(數據, 「UTF8」,TR? makeHash)作爲output.write的參數?在這種情況下,程序不起作用,TypeError:無法讀取未定義的屬性'length' –

回答

0

我的錯誤#1是我創建了一個讀取流 - 相反,我應該聲明變量輸入讀取文件,並在回調中使用變換流來寫入其內容。

錯誤#2是我錯誤地實現了函數makeHash:現在它完美的加密和寫入文件。所以這個函數被稱爲_transform函數的回調函數。

Here's工作代碼:

"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}`); 
});