简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM