手动实现转换流
stream.Transform 类继承自 stream.Duplex,并且实现了自有的 writable._write() 和 readable._read() 方法。 自定义的转换流必须实现 transform._transform() 方法,transform._flush() 方法是可选的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| const crypto = require("crypto"); const fs = require("fs"); const { Transform } = require("stream"); var pwd = "12345678"; //秘钥必须为:8/16/32位
class DecryptFileStream extends Transform { constructor(aes) { super(); if (aes) { const key = Buffer.from(aes, "base64"); const decipher = crypto.createDecipheriv("aes-128-ecb", key, ""); decipher.setAutoPadding(true); this._decipher = decipher; } else { this._decipher = null; } } }
DecryptFileStream.prototype._transform = function (data, encoding, callback) { if (this._decipher) { this.push(this._decipher.update(data)); } else { this.push(data); } callback(); };
DecryptFileStream.prototype._flush = function (data, encoding, callback) { if (this._decipher) { this.push(this._decipher.final()); } callback(); };
const readS = fs.createReadStream("./2.jpeg"); const writeS = fs.createWriteStream("./4.jpeg"); const decryptStream = new DecryptFileStream(pwd); readS.pipe(decryptStream).pipe(writeS);
|