4

In my node.js app I would like to upload a file and calculate the sha1 .

I tried the following :

export function calculateHash(file, type){
  const reader = new FileReader();
  var hash = crypto.createHash('sha1');
  hash.setEncoding('hex');
  const testfile = reader.readAsDataURL(file);
  hash.write(testfile);
  hash.end();
  var sha1sum = hash.read();
  console.log(sha1sum);
  // fd.on((end) => {
  //   hash.end();
  //   const test = hash.read();
  // });
}

The file is blob from selecting a file with a file upload button on my website.

How can I calculate the sha1 hash?

2
  • CryptoJS is mainly a client library and should not be confused with node.js' crypto module. Which one is it for you? Commented Jun 16, 2016 at 20:40
  • What's the issue with the code you've presented here? Doesn't it already work? Commented Jun 16, 2016 at 20:41

1 Answer 1

5

if you're reading the contents in as a block, you're making this harder than it needs to be. We do this:

const fs = require('fs');
export function calculateHash(file, type){
  const testFile = fs.readFileSync(file);
  var sha1sum = crypto.createHash('sha1').update(testFile).digest("hex");
  console.log(sha1sum);
}
Sign up to request clarification or add additional context in comments.

2 Comments

The solution generated an error. Cannot read property 'length' of undefined
Works fine for me once the spelling is fixed for testfile and testFile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.