Streaming data to/from file in browser

632 Views Asked by At

Is there an API in the browser (outside of websockets) which allows us to stream data from a file to the browser? something like this:

const reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.on('data', d => {            // imaginary api 
   // new line of data d
});

what could happen is the user selects the local file, and some process on the local OS writes to it. If this doesn't work, then websockets is an option.

1

There are 1 best solutions below

1
david-ao On BEST ANSWER

Browsers can consume streaming data using the Streams API, here how to use it, from those links:

The basic usage of Streams hinges around making responses available as streams. For example, the response body returned by a successful fetch request can be exposed as a ReadableStream, and you can then read it using a reader created with ReadableStream.getReader(), cancel it with ReadableStream.cancel()

// Fetch the original image
fetch('./tortoise.png')
// Retrieve its body as ReadableStream
.then((response) => {
   const reader = response.body.getReader();
   // …
 });

A good post about the Streams API

Another option could be using server sent events implementing the "streaming" as a sequence of reactions to events (new lines from the file?), still from mdn links EventSource Interface:

Unlike WebSockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form.

Here a link to another question with a lot of cool info and links

These solutions involve some Server side work of course