I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code:
const writable = await fileHandle.createWritable();
Every time I try to execute it, I keep getting this error message:
TypeError: fileHandle.createWritable is not a function
Oddly enough, when I run the same command in the console, it works without any problems.
Just to provide some context, I'm working on Windows 10. Any assistance would be greatly appreciated. Thank you!
Below are the relevant snippets of my HTML and 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)