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:
- I know I could simply use
Buffer.sliceto solve it, butBuffer.sliceis now deprecated. Is there a way to do exactly the same asBuffer.slice? - In Approach 2, why is the
file.bufferusing more bytelength? - Is it not recommended to use
Bufferhere? I didn't expect theTypeErroroccurs in Approach 3. - 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.