是否可以使用文件系统访问 API 来查看文件?

Sco*_*sey 5 javascript google-chrome-extension file-system-access-api

我正在开发一个 chrome 扩展,它会提示用户输入一个目录,然后将特定文件从该目录上传到该扩展处于活动状态的网站。理想情况下,当这些文件在用户驱动器上发生更改时,此扩展程序会自动上传这些文件。通过文件系统访问 API,我可以设置一个系统,在其中可以轮询文件的内容以查看它们是否已更改:

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.
}
Run Code Online (Sandbox Code Playgroud)

是否有一种watch()埋藏在 API 文档中我还没有找到的方法,或者扩展程序可以通过其他方式监视文件状态而不需要不断轮询。

Den*_*er9 3

现在无法监视文件,但有一个关于文件更改事件的建议,这将允许您将来执行此操作。