mailman_73
mailman_73

Reputation: 798

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'))
});

Upvotes: 2

Views: 7159

Answers (2)

Lucky Soni
Lucky Soni

Reputation: 6878

var rs = fs.createReadStream('./passwords.txt');
var ws = fs.createWriteStream('./new_passwords.txt');
var Transform = require('stream').Transform;
var transformer = new Transform();

transformer._transform = function(data, encoding, cb) {
 // do transformation
 cb();
}

    rs
    .pipe(transformer)
    .pipe(ws);

Upvotes: 2

idbehold
idbehold

Reputation: 17168

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)

Upvotes: 5

Related Questions