简体   繁体   中英

Read a local text file constantly

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM