我目前正在为未来的项目掌握文件系统访问 API,并且在使用以下行中的 createWritable() 方法时遇到了困难:
const writable = await fileHandle.createWritable();
当我触发它时,它给了我错误:
TypeError: fileHandle.createWritable is not a function
但是,当我在控制台中运行这个确切的命令时,它可以完美运行。
如果这完全相关,我正在使用 Windows 10。谢谢您的帮助。
我将在下面包含我的相关 HTML 和 JS:
HTML:
<body>
<h1>Hello There</h1>
<button class="read-btn">Read</button>
<textarea id="txt"></textarea>
<button class="create-btn">Create</button>
<button class="write-btn">Write</button>
</body>
<script src="./index.js"></script>
JS:
const readBtn = document.querySelector(".read-btn");
const createBtn = document.querySelector(".create-btn")
const writeBtn = document.querySelector(".write-btn");
const txt = document.querySelector("#txt");
// Store a ref to file handle
let fileHandle;
let contents;
// === READ FROM A FILE SYSTEM ===
readBtn.addEventListener("click", async () => {
// open filepicker
[fileHandle] = await window.showOpenFilePicker();
// Returns a file object
const file = await fileHandle.getFile();
// Runs text method on returned file object to access text
contents = await file.text();
// Inputs contents into txt
txt.value = contents;
});
// === WRITE TO FILESYSTEM ===
// Create a new file
async function getNewFileHandle() {
const options = {
types: [
{
description: 'Text Files',
accept: {
'text/plain': ['.txt'],
},
},
],
};
const handle = await window.showSaveFilePicker(options);
return handle;
}
// Save changes to disk
async function writeFile(fileHandle) {
contents = txt.value;
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the file and write the contents to disk.
await writable.close();
}
createBtn.addEventListener("click", getNewFileHandle)
writeBtn.addEventListener("click", writeFile)