I'm currently getting to grips with the File System Access API for a future project, and I am having difficulty using the createWritable() method in the line:
const writable = await fileHandle.createWritable();
When I trigger it, it gives me the error:
TypeError: fileHandle.createWritable is not a function
However, when I run this exact command in the console, it works perfectly.
I'm using windows 10 if that's relevant at all. Thanks for the help.
I will include my relevant HTML and JS below:
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)
According to MDN documentation, window.showOpenFilePicker
, FileSystemFileHandle
, and FileSystemWritableFileStream
are only supported in secure contexts:
Secure context
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
It's my understanding that the "Live Server" extension for VS Code would not meet this requirement, but the developer console would.