mailman_73 mailman_73 - 21 days ago 7
Node.js Question

Node: Read data, transform it and write into file using streams and pipe

I try to read a string from a text file, encode it and save into a file. I wanna use

pipe
in order to transfer
hash
from
ReadStream
to
WriteStream
. But I don't know how to transform the changed data. My code:

const crypto = require('crypto');
const fs = require('fs');
let hash = crypto.createHash('md5');
var rs = fs.createReadStream('./passwords.txt');
var ws = fs.createWriteStream('./new_passwords.txt');


rs.on('data', function(d) {
hash.update(d);
});
rs.on('end', function(d) {
console.log(hash.digest('hex'))
});

Answer

According to the documentation it should be as easy as:

const fs = require('fs')
const crypto = require('crypto')
const hash = crypto.createHash('md5')
const rs = fs.createReadStream('./plain.txt')
const ws = fs.createWriteStream('./hashed.txt')

rs.pipe(hash).pipe(ws)