Using Buffer in Electron

93 views Asked by At

I'm working on an Electron app that read and modify files and show the result in the browser.

The modify function seems like:

const offset = 16;
let file = readFileSync('<some-file>');

if (condition) {
    return file.subarray(offset);
}

return file;

In the frontend, I'm doing this:

new Blob(
    [file.buffer],
    { type }
)

The file.buffer is causing the problem after file.subarry() as it's still using the original reference.

Original:

console.log(file.length, file.buffer.byteLength); // 4075, 4091 (included the offset that should have trimmed)

Approach 1:

file.slice(offset);
console.log(file.length, file.buffer.byteLength); // 4075, 4075 (everything works fine)

Approach 2:

Buffer.from(file, offset, file.length - offset); // or
Buffer.copyBytesFrom(file, offset, file.length - offset);
console.log(file.length, file.buffer.byteLength); // 4075, 8192 (???)

Approach 3:

let buffer = Buffer.alloc(file.length - offset);
file.copy(buffer, 0, offset, file.length - offset); // TypeError: file.copy is not a function at __webpack_modules__../src.....

Question:

  1. I know I could simply use Buffer.slice to solve it, but Buffer.slice is now deprecated. Is there a way to do exactly the same as Buffer.slice?
  2. In Approach 2, why is the file.buffer using more bytelength?
  3. Is it not recommended to use Buffer here? I didn't expect the TypeError occurs in Approach 3.
  4. Following question 3, I've tried to rewrite the function with Uint8Array, and do the modification in the browser. The function works but when I replace the script for Electron, something related to buffer went wrong. Is there a better way to get rid of the buffer problems?

PS. This application is written in Typescript. I tried to install the NPM module buffer to polyfill(?) and hope it will solve the TypeError issue in Approach 3. But before I compile the code, Typescript is complaining everywhere.

0

There are 0 answers