nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
106.71k stars 29.1k forks source link

Accept `Blob`s anywhere where a `Buffer` is currently accepted for writing #53090

Open danfuzz opened 4 months ago

danfuzz commented 4 months ago

What is the problem this feature will solve?

Because Buffers aren't immutable, any time a Buffer is passed to something which will perform an asynchronous write, there is a concurrency hazard where the buffer could conceivably get modified before it gets a chance to be written. This can lead to bugs which are hard to track down. (I speak from experience.)

What is the feature you are proposing to solve the problem?

Anywhere where Buffer is currently accepted for a write operation, e.g. and perhaps most notably stream.Writable.write() and stream.Writable.end(), also make it acceptable to pass a Blob. Blobs are always immutable.

What alternatives have you considered?

Just keep using Buffers, mostly keep my fingers crossed, and sometimes make copies of Buffers as a safeguard.

(Note: It also makes sense to have a way to optionally have Blobs returned from readable streams, but I figure that'd be a different feature request.)

Jamesernator commented 4 months ago

Just keep using Buffers, mostly keep my fingers crossed, and sometimes make copies of Buffers as a safeguard.

You can transfer array buffers into your control with the method of the same name:

const buffer = Buffer.alloc(100);

const transferredBytes = new Uint8Array(buffer.buffer.transfer());
buffer[0] = 12; // Effectively a no-op now
console.log(transferredBytes[0]); // 0

Regardless I agree that generally all buffer-like things should be accepted in all writer-like functions (the web does this).