2

I'm a little lost on how I can read a local text file constantly. Nothing is going to a webserver, everything is done locally and its just something basic.

Essentially I have a text file that is getting updated constantly (A different program is writing to the text file), and I want to be able to read that text file. I just want to do something basic where a div gets auto updated with text file content without refreshing the page.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
Jith
  • 99
  • 5

1 Answers1

4

Thanks to the File System Access API we can now keep live links to resources on the disk and request their content when we wish. (Previously, Files only kept a snapshot of a file on disk).

So in modern Chrome we can now request access to a file on disk using the window.showOpenFilePicker method.
This will return a list of handles, from which we will be able to call the getFile() method to get an up-to-date snapshot of the file on disk.

// must come from an user gesture
onclick = async () => {
  
  if( !("showOpenFilePicker" in self) ) {
    throw new Error( "unsupported browser" );
  }

  const handles = await showOpenFilePicker();
  
  setInterval( async () => {
    const file = await handles[0].getFile();
    document.getElementById( "log" ).textContent = await file.text();
  }, 1000 );
  
};

Since this API is over-protected, it can't run in cross-domain iframes, so here is an outsourced glitch demo, which currently works only in Chrome.

Kaiido
  • 123,334
  • 13
  • 219
  • 285