This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.
The WritableStream interface of the the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with build-in backpressure and queuing.
Constructor
WritableStream.WritableStream()- Creates a new
WritableStreamobject.
Properties
WritableStream.lockedRead only- A boolean indicating whether the
WritableStreamis locked to a writer.
Methods
WritableStream.abort()- Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
WritableStream.getWriter()- Returns a new instance of
WritableStreamDefaultWriterand locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released.
Examples
The following example illustrates several features of this interface. It shows the creation of the WritableStream with a custom sink (destination) and an API-supplied queueing strategy (lines 10 through 12). It then calls a function called arrayToStream(), passing the newly created stream and an array of integers (line 14). Inside this function it calls the streams getWriter() method, which returns an instance WritableStreamDefaultWriter. A forEach() call is used to write each chunk of the array to the stream. Finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams (lines 4-5 and 15-16).
function arrayToStream(array, writableStream) {
const writer = writableStream.getWriter();
array.forEach(chunk => writer.write(chunk)
.then(() => console.log("Chunk written to sink.))
.catch(e => console.error("Chunk writing error: " + e));
);
// Returns a promise.
return writer.close();
}
var sink = new MySink();
var strategy = new ByteLengthQueuingStrategy({ highWaterMark: 32 * 1024 })
const writableStream = new WritableStream(sink, strategy);
arrayToStream([1,2,3,4,5], writableStream)
.then(() => console.log("All chunks written. Stream closed."))
.catch(e => console.error("Stream writing error: " + e));
Specifications
| Specification | Status | Comment |
|---|---|---|
| Streams The definition of 'WritableStream' in that specification. |
Living Standard | Initial definition. |
Browser Compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | 58 | ? | ? | 45 | ? |
| Feature | Android Webview | Chrome for Android | Firefox Mobile (Gecko) | Firefox OS | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|
| Basic support | 58 | 58 | ? | ? | ? | 45 | ? |