Skip to content

Instantly share code, notes, and snippets.

@mekarpeles
Created March 2, 2025 20:09
Show Gist options
  • Save mekarpeles/db2cc61a55c62ef3a4204ef72530fb42 to your computer and use it in GitHub Desktop.
Save mekarpeles/db2cc61a55c62ef3a4204ef72530fb42 to your computer and use it in GitHub Desktop.
JS File System Access API
<button id="pick-folder">Select Open Library Folder</button>
<ul id="file-list"></ul>
<script type="text/javascript">
async function getStoredDirectory() {
if ("storage" in navigator && "getDirectory" in navigator.storage) {
try {
const dirHandle = await navigator.storage.getDirectory();
return dirHandle.getFileHandle("selected-folder").catch(() => null);
} catch (err) {
console.warn("Could not retrieve stored folder:", err);
}
}
return null;
}
async function saveDirectoryHandle(dirHandle) {
try {
const dir = await navigator.storage.getDirectory();
await dirHandle.requestPermission({ mode: "read" });
await dir.addEntry("selected-folder", dirHandle);
} catch (err) {
console.warn("Could not save folder handle:", err);
}
}
async function listFiles(dirHandle) {
const fileList = document.getElementById("file-list");
fileList.innerHTML = "";
for await (const entry of dirHandle.values()) {
const li = document.createElement("li");
li.textContent = entry.name;
fileList.appendChild(li);
}
}
async function loadFilesOnStartup() {
const storedHandle = await getStoredDirectory();
if (storedHandle) {
console.log("Using stored directory handle...");
listFiles(storedHandle);
}
}
document.getElementById("pick-folder").addEventListener("click", async () => {
try {
const dirHandle = await window.showDirectoryPicker();
await saveDirectoryHandle(dirHandle);
listFiles(dirHandle);
} catch (err) {
console.error("Error accessing folder:", err);
}
});
// Try to auto-load files if permission is granted
loadFilesOnStartup();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment