Scott Casey
Scott Casey

Reputation: 85

Is it possible to use the File System Access API to watch a file?

I am working on a chrome extension that will prompt a user for a directory and then will upload specific files from that directory to the site that the extension is active on. Ideally, this extension would automatically upload these files when they change on the user's drive. With the File System Access API, I can setup a system where I can poll the contents of the file to see if they've changed:

const handles = {
  translation:{handle:null,text:''},
  html:{handle:null,text:''},
  css:{handle:null,text:''}
};
//updateDirectory is triggered by clicking on a "select directory" button
async function updateDirectory(){
  const directoryHandle = await window.showDirectoryPicker();
  Object.keys(handles).forEach((key)=>handles[key] = null);//Clear the preexisting handles.
  //Get the handles for the individual files/directories
  if(handles.interval){
    clearInterval(handles.interval);
  }
  for await (let handle of directoryHandle.values()){
    if(handle.kind === 'file'){
      console.log('handle.name:',handle.name);
      if(handle.name === 'translation.json'){
        handles.translation.handle = handle;
      }else if(handle.name.endsWith('.html')){
        handles.html.handle = handle;
      }else if(handle.name.endsWith('.css')){
        handles.css.handle = handle;
      }
    }
  }
  startFilePoll();
}

function startFilePoll(){
  handles.interval = setInterval(updateSheet,5000);//Check files every 5 seconds
}

async function updateSheet(){
  const filePromises = Object.entries(handles).map(async ([fileType,handle])=>{
    const file = await handle.getFile();
    const text = await file.text();
    if(text !== handles[fileType].text){
      //upload file changes
    }
  });
  await Promise.all(filePromises);
  //Do other things with the changed files.
}

Is there a watch() method buried in the API documentation that I just haven't found, or some other way for the extension to monitor the file states without needing to constantly poll.

Upvotes: 5

Views: 1981

Answers (2)

Mulhoon
Mulhoon

Reputation: 1902

There is currently a trial for this in Chrome.

To test the File System Observer API locally, set the #file-system-observer flag in about:flags. https://developer.chrome.com/blog/file-system-observer

Upvotes: 0

DenverCoder9
DenverCoder9

Reputation: 2577

There is no way to watch files now, but there's a proposal for file change events which will allow you to do that in the future.

Upvotes: 3

Related Questions