0
async function parseFile(file, type) {
  const fileSize = file.size;
  const chunkSize = 1024 * 1024; // bytes
  let offset = 0;
  let chunkReaderBlock = null;
  const hash = sha1.create();
  const ansList = [];

  const readEventHandler = async function (evt) {
    if (evt.target.error == null) {
      offset += evt.target.result.length;
      await hash.update(evt.target.result);
    } else {
      console.log('Read error: ' + evt.target.error);
      return;
    }
    if (offset >= fileSize) {
      const ans = await hash.hex();
      console.log(ans);
      ansList.push(ans);
      if (type.localeCompare('multiple') === 0) {
        filesUploadHashes.PostFiles.push(ans);
      } else {
        filesUploadHashes.Thumbnail.push(ans);
      }
      return;
    }

    // of to the next chunk
    await chunkReaderBlock(offset, chunkSize, file);
    return ansList;
  };

  chunkReaderBlock = async function (_offset, length, _file) {
    const reader = new FileReader();
    const blob = await _file.slice(_offset, length + _offset);
    reader.onload = readEventHandler;
    await reader.readAsText(blob);
  };

  // read with the first block
  await chunkReaderBlock(offset, chunkSize, file);
  return ansList;
}

parseFile() fucntion takes in a file and reads it chunk by chunk(using offset) by FileReader calculating the sha1 hash. The hash when done calculated is being pushed to ansList array. When printing the array, the output is fine but the length is coming out to be 0.

const ansList = await parseFile(e.target.files[0], '');
console.log(ansList, ansList.length);

console.log() output

3
  • 1
    await reader.readAsText(blob); does not work, readAsText does not return a promise. Commented Jul 10, 2022 at 18:51
  • @Bergi Do I have an alternative? Commented Jul 13, 2022 at 16:22
  • 1
    Either properly promisify the FileReader's onload callback, or just use blob.text() instead. Commented Jul 13, 2022 at 17:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.