Martin White
Martin White

Reputation: 3

Remove or change original data from stream Nodejs

I have a code to write a hash to the file from text of another file, but the problem is that in resulting file is written not only hash, but also the original text.

For example: if content of source file qwerty a got in result file qwertyd8578edf8458ce06fbc5bb76a58c5ca4, but i need just d8578edf8458ce06fbc5bb76a58c5ca4.

const fs = require('fs');
const crypto = require('crypto');
const hash = crypto.createHash('MD5');

const readData = fs.createReadStream('./task1/input.txt');
const writeData = fs.createWriteStream('./task1/output.txt');

readData.on('data', (chunk) => {
    hash.update(chunk);
});

readData.on('end', () => {
    const resultHash = hash.digest('hex');
    writeData.end(resultHash);
    console.log(resultHash);
});

readData.pipe(writeData);

How i can fix this? Thanks.

Upvotes: 0

Views: 838

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138307

If you want to hash a stream, thats super easy as hash is itself a stream ( a Transform stream). Just pipe your input into it, and pipe the resulting hash into your output:

 const fs = require('fs');
 const crypto = require('crypto');
 const hash = crypto.createHash('MD5');

  const readData = fs.createReadStream('./task1/input.txt');
 const writeData = fs.createWriteStream('./task1/output.txt');

 readData.pipe(hash).pipe(writeData);

Reference

Upvotes: 1

Related Questions