Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...