[英]The File System Access API file writing gives error
When i run the following program:当我运行以下程序时:
JS: 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: HTML:
<button onclick = "write();">
write file
</button>
I get the following error:我收到以下错误:
[Violation] Avoid using document.write().
【违规】避免使用document.write()。 https://developers.google.com/web/updates/2016/08/removing-document-write
https://developers.google.com/web/updates/2016/08/removing-document-write
I clicked the link and it was no help, and i got the same error when using document.append, even though document.write was not used.我单击了该链接,但没有任何帮助,并且在使用 document.append 时遇到了同样的错误,即使没有使用 document.write。
I'm still a newbie to the File System Access API, and need help.我还是文件系统访问 API 的新手,需要帮助。 Thank you all!
谢谢你们!
Edit: i have found out that naming a function 'write' is enough to trigger the document.write detection, but even after renaming the function, i now get the error:编辑:我发现命名 function 'write' 足以触发 document.write 检测,但即使在重命名 function 之后,我现在也得到错误:
Uncaught (in promise) TypeError: filehandle.createWritable is not a function
Uncaught (in promise) TypeError: filehandle.createWritable is not a function
The window.showOpenFilePicker()
method returns a promise with an array of file handles according to the docs : window.showOpenFilePicker()
方法根据文档返回带有文件句柄数组的 promise :
This means you should fulfill the promise (using await
or chaining it with a then
:这意味着您应该满足 promise (使用
await
或将其与then
链接:
async function write(){
const filehandle = await window.showOpenFilePicker();
// rest of code...
}
Other than that, showOpenFilePicker
returns an array containing the file handles.除此之外,
showOpenFilePicker
返回一个包含文件句柄的数组。 It needs to be retrieved from the array before you can create a writable.在创建可写对象之前,需要从数组中检索它。 You can use array destructuring to do exactly that:
您可以使用数组解构来做到这一点:
async function write(){
const [filehandle] = await window.showOpenFilePicker();
const writable = await filehandle.createWritable();
await writable.write('The file has been updated');
await writable.close();
}
And that should do the trick.这应该可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.