I'm working with Web Workers and Buffers recently.
Now I have a buffer and I want to check the sixth byte using SmartBuffer. If that byte is 0, send to worker1. Otherwise, send to worker2.
const buffer = SmartBuffer.fromBuffer(someBuffer);
if(buffer.toBuffer()[5] === 0){
worker1.postMessage(someBuffer, [someBuffer]);
}
if(buffer.toBuffer()[5] === 1){
worker2.postMessage(someBuffer, [someBuffer]);
}
Since I use a transferable object, if the someBuffer
has been transferred, I cannot access it in line 5 anymore. (It'll cause an error: Cannot perform Construct on a detached ArrayBuffer
.)
I know that's a bad example, and I can simply use else if
to prevent this error. But the question is: Is there any way to know if a buffer has been transferred?
The byteLength
property of a detached ArrayBuffer and each typed array which uses this ArrayBuffer will be zero.
I'm not sure about the internals of the SmartBuffer library but this check should work:
someBuffer.byteLength === 0
This does of course not help if you want to check an ArrayBuffer which has an initial byteLength of zero. In this case nothing will change if it gets detached. But I think this is only a problem in theory.