In NodeJS, writing blob data to a file results in corrupt file

52 views Asked by At

I'm writing an application using Electron, TypeScript, React, and hls.js. I implemented a version of this post here which can download a file using the anchor tag. However, in my new implementation, every time I download video or audio, it results in a corrupt file. I'm not sure what's going wrong.

Code from renderer:

useEffect(() => {
    const hls = hlsRef.current;
    if (!hls) return;

    // If recording, append buffer data to the data stream
    if (isRecording) {
      const recordStream = (
        _: typeof Hls.Events.BUFFER_APPENDING,
        { data, type }: BufferAppendingData
      ) => dataStream.current[type].push(data);

      hls.on(Hls.Events.BUFFER_APPENDING, recordStream);

      return () => hls.off(Hls.Events.BUFFER_APPENDING, recordStream);
    }

    // Since we're not recording, make sure we have data in the data stream,
    // if we do, send it to main
    if (dataStream.current.video.length > 0) {
      const sendStreamData = async () => {
        await window.electronAPI.handleFileDownload({
          video: arrayRecord.current[0].data.video,
          audio: arrayRecord.current[0].data.audio,
          audiovideo: []
        });
      };

      sendStreamData();
    }
  }, [isRecording]);

Code that is run in main:

const arrayConcat = (input: Uint8Array[]) => {
  const totalLength = input.reduce((prev, curr) => prev + curr.length, 0);
  const result = new Uint8Array(totalLength);

  let offset = 0;
  input.forEach((el) => {
    result.set(el, offset);
    offset += el.length;
  });

  return result;
}

const downloadVideo = async (videoData: Uint8Array[]) => {
  const blob = new Blob([arrayConcat(videoData)], {
    type: "application/octet-stream"
  });
  const output = "out/video.mp4";

  const buffer = Buffer.from(await blob.arrayBuffer());
  fs.writeFileSync(output, buffer);
}

After running the above code, I got an mp4 which could not be played, whereas after running the code from the post that I followed, the mp4 downloaded and played without issue. Essentially, all I'm trying to do is replace the download via anchor tag with downloading through node's file system.

0

There are 0 answers