繁体   English   中英

文件系统访问 API 文件写入给出错误

[英]The File System Access API file writing gives error

当我运行以下程序时:

JS:

async function write(){
  const filehandle = window.showOpenFilePicker();
  const writable = await filehandle.createWritable();
  await writable.write('The file has been updated');
  await writable.close();
}

HTML:

<button onclick = "write();">
write file
</button>

我收到以下错误:

【违规】避免使用document.write()。 https://developers.google.com/web/updates/2016/08/removing-document-write

我单击了该链接,但没有任何帮助,并且在使用 document.append 时遇到了同样的错误,即使没有使用 document.write。

我还是文件系统访问 API 的新手,需要帮助。 谢谢你们!

编辑:我发现命名 function 'write' 足以触发 document.write 检测,但即使在重命名 function 之后,我现在也得到错误:

Uncaught (in promise) TypeError: filehandle.createWritable is not a function

window.showOpenFilePicker()方法根据文档返回带有文件句柄数组的 promise

这意味着您应该满足 promise (使用await或将其与then链接:

async function write(){
  const filehandle = await window.showOpenFilePicker();
  // rest of code...
}

除此之外, showOpenFilePicker返回一个包含文件句柄的数组 在创建可写对象之前,需要从数组中检索它。 您可以使用数组解构来做到这一点:

async function write(){
  const [filehandle] = await window.showOpenFilePicker();
  const writable = await filehandle.createWritable();
  await writable.write('The file has been updated');
  await writable.close();
}

这应该可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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