From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- files/pt-br/web/api/streams_api/index.html | 157 +++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 files/pt-br/web/api/streams_api/index.html (limited to 'files/pt-br/web/api/streams_api/index.html') diff --git a/files/pt-br/web/api/streams_api/index.html b/files/pt-br/web/api/streams_api/index.html new file mode 100644 index 0000000000..c382b3e7f8 --- /dev/null +++ b/files/pt-br/web/api/streams_api/index.html @@ -0,0 +1,157 @@ +--- +title: Streams API +slug: Web/API/Streams_API +tags: + - API + - Experimental + - Landing + - NeedsTranslation + - Reference + - Streams + - TopicStub +translation_of: Web/API/Streams_API +--- +
{{SeeCompatTable}}{{APIRef("Streams")}}
+ +
A API Streams permite que o JavaScript acesse programaticamente fluxos de dados recebidos pela rede e os processe conforme desejado pelo desenvolvedor.
+ +

+ +

Conceitos e Uso

+ + + +

O streaming envolve a divisão de um recurso que você deseja receber pela rede em pequenos blocos e, em seguida, processa esses blocos aos poucos. Isso é algo que os navegadores fazem de qualquer maneira ao receber recursos para serem exibidos em páginas da web — o buffer de vídeos e mais está gradualmente disponível para reprodução, e às vezes você verá imagens sendo exibidas gradualmente conforme mais é carregado.

+ +

Mas isto nunca esteve disponível para JavaScript antes. Anteriormente, se quiséssemos processar um recurso de algum tipo (seja ele um vídeo, ou um arquivo de texto, etc.), Teríamos que baixar o arquivo inteiro, espera até que seja desserializado em um formato adequado, então processa todo o lote após ser totalmente recebido.

+ +

Com o Streams disponível para JavaScript, tudo isso muda - agora você pode começar a processar dados brutos com JavaScript bit a bit assim que estiverem disponíveis no lado do cliente, sem a necessidade de gerar um buffer, string ou blob.

+ +

+ + + +

Também há mais vantagens - você pode detectar quando os fluxos começam ou terminam, encadeia os fluxos juntos, trata os erros e cancela os fluxos quando necessário e reage à velocidade em que o fluxo está sendo lido.

+ +

O uso básico de Streams gira em torno de tornar as respostas disponíveis como streams. Por exemplo, a resposta {{domxref("Body")}} retornada com sucesso de uma fetch request pode ser exposta como um {{domxref("ReadableStream")}}, e você pode lê-lo usando um leitor criado com {{domxref("ReadableStream.getReader()")}}, cancela-lo com {{domxref("ReadableStream.cancel()")}}, etc.

+ + + +

Usos mais complicados envolvem a criação de seu próprio fluxo usando o contrutor {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}}, por exemplo para processar dados dentro de um service worker.

+ +

Você também pode gravar dados em streams usando {{domxref("WritableStream")}}.

+ +
+

Note: Você pode encontrar muito mais detalhes sobre a teoria e prática de streams em nossos artigos — Streams API concepts, Using readable streams, e Using writable streams.

+
+ +

Stream interfaces

+ +

Readable streams

+ +
+
{{domxref("ReadableStream")}}
+
Represents a readable stream of data. It can be used to handle response streams of the Fetch API, or developer-defined streams (e.g. a custom {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor).
+
{{domxref("ReadableStreamDefaultReader")}}
+
Represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request).
+
{{domxref("ReadableStreamDefaultController")}}
+
Represents a controller allowing control of a {{domxref("ReadableStream")}}'s state and internal queue. Default controllers are for streams that are not byte streams.
+
+ +

Writable streams

+ +
+
{{domxref("WritableStream")}}
+
Provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
+
{{domxref("WritableStreamDefaultWriter")}}
+
Represents a default writable stream writer that can be used to write chunks of data to a writable stream.
+
{{domxref("WritableStreamDefaultController")}}
+
Represents a controller allowing control of a {{domxref("WritableStream")}}'s state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
+
+ + + +
+
{{domxref("ByteLengthQueuingStrategy")}}
+
Provides a built-in byte length queuing strategy that can be used when constructing streams.
+
{{domxref("CountQueuingStrategy")}}
+
Provides a built-in chunk counting queuing strategy that can be used when constructing streams.
+
+ +

Extensions to other APIs

+ +
+
{{domxref("Request")}}
+
When a new Request object is constructed, you can pass it a {{domxref("ReadableStream")}} in the body property of its RequestInit dictionary.  This Request could then be passed to a {{domxref("WindowOrWorkerGlobalScope.fetch()")}} to commence fetching the stream.
+
{{domxref("Body")}}
+
The response {{domxref("Body")}} returned by a successful fetch request is exposed by default as a {{domxref("ReadableStream")}}, and can have a reader attached to it, etc.
+
+ + + +
+

Important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. This may change over time.

+
+ +
+
{{domxref("ReadableStreamBYOBReader")}}
+
Represents a BYOB ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor).
+
{{domxref("ReadableByteStreamController")}}
+
Represents a controller allowing control of a {{domxref("ReadableStream")}}'s state and internal queue. Byte stream controllers are for byte streams.
+
{{domxref("ReadableStreamBYOBRequest")}}
+
Represents a pull into request in a {{domxref("ReadableByteStreamController")}}.
+
+ +

Examples

+ +

We have created a directory of examples to go along with the Streams API documentation — see mdn/dom-examples/streams. The examples are as follows:

+ + + +

Examples from other developers:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Streams')}}{{Spec2('Streams')}}Initial definition.
+ +

Browser compatibility

+ + + +

WritableStream

+ +

{{Compat("api.WritableStream")}}

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf