Question:
Fix: Incorrect NodeJS Crypto Hash when using ReadableStream.pipe

f1 and f2 process data streams differently. For the f2 you can't use the digest with the pipe. The pipe returns a writable steam.


Try this code:

import { createHash } from 'node:crypto';

import { Readable } from 'node:stream';


function f1(info: NodeJS.ReadableStream) {

  return new Promise((resolve, reject) => {

    const hash = createHash('sha256');


    info.on('data', (data) => hash.update(data));

    info.on('end', () => resolve(hash.digest('hex')));

    info.on('error', (error) => reject(error));

  });

}


function f2(info: NodeJS.ReadableStream) {

  const hasher = createHash('sha256');

  return new Promise((resolve, reject) => {

    info.pipe(hasher)

      .on('finish', () => resolve(hasher.digest('hex')))

      .on('error', (error) => reject(error));

  });

}

export async function test() {

  const h1 = await f1(Readable.from('Testing'));

  const h2 = f2(Readable.from('Testing'));


  console.log(h1);

  console.log(h2);

}


test();


Answered by:> spjdev

Credit:> StackOverflow


Blog Links: 

>Why Swagger UI does not show the Choose a File button?

>How to measure the time queries take to run in NodeJS?

>While npm run dev do nothing and crash in Nodejs?

>How to update a document in MongoDB with NodeJS?

>How can I write a new file in Nodejs?

>How to overwrite the contents of MongoDB via a put request in Nodejs?

>NodeJS Error Solved: Handling Not Sending Error To Frontend

>How to wait until I have my uploaded URL?


Nisha Patel

Nisha Patel

Submit
0 Answers