Opening Local Folders from a Web App
Open local folders in a web app with the File System Access API. List, read, edit and save files, restore folder access, and handle browser support.
The File System Access API lets a web app open a folder the user picks with window.showDirectoryPicker(), list its contents through a FileSystemDirectoryHandle, read files with getFile(), and write them back with createWritable(). Nothing reaches the disk until you call close().
If you build a notes editor, a log viewer or an image organiser, upload forms are a poor fit. Users already keep these files in folders, and they expect your tool to edit those folders directly, not hand them copies to download. This article builds one small Markdown notes app that does that. It opens a folder, lists the .md files, edits one, saves it back, and reopens the same folder on the next visit. The app works on real folders the user can see. If you need storage the browser keeps hidden instead, see running SQLite in the browser with OPFS.
Key Takeaways
showDirectoryPicker()needs a secure context and a user gesture such as a button click. Without the gesture, it throwsSecurityError.- An
AbortErrorfromshowDirectoryPicker()means no folder is available. Return to idle and don’t show an error. - Writes made through a
FileSystemWritableFileStreamland on disk only whenclose()resolves. - You can store a
FileSystemDirectoryHandlein IndexedDB. On a later visit, check it withqueryPermission()and ask again withrequestPermission()from a click. <input type="file" webkitdirectory>works in all major browsers, but it only reads. To save on that path, you have to download a Blob.
What Does the File System Access API Make Possible?
With the File System Access API, a web app can open a folder the user chooses, read every file in it, and, once the user grants write permission, save changes to those same files. In the notes app, the user picks ~/Documents/notes. The app lists ideas.md and todo.md, the user edits one in a textarea, and Save overwrites the original file. No copy lands in Downloads. The picker comes from the WICG File System Access spec. Handles, reading and writing come from the WHATWG File System Standard.
Open a Folder From a Button Click
To open a local folder, call window.showDirectoryPicker() inside a click handler, after checking that the API exists. MDN documents three options:
idmakes the picker remember the last location it used.modeis'read'by default, or'readwrite'.startInis a well-known folder such as'documents'.
The method resolves to a FileSystemDirectoryHandle.
const supportsFSA = 'showDirectoryPicker' in window && window.self === window.top;
let notesDir; // FileSystemDirectoryHandle
let currentFile; // FileSystemFileHandle
openBtn.addEventListener('click', async () => {
try {
notesDir = await window.showDirectoryPicker({
id: 'notes', mode: 'readwrite', startIn: 'documents',
});
} catch (err) {
if (err.name === 'AbortError') return; // no folder; stay idle
throw err;
}
await saveHandle(notesDir);
await listNotes(notesDir);
});
showDirectoryPicker() only works in a secure context and must be called from a user gesture. If you call it on page load, it throws a SecurityError, and the same-origin policy produces the same error in a cross-origin iframe. The window.self === window.top check rejects every iframe, which is stricter than the policy requires. That check is the detection approach used in the web.dev open-a-directory pattern.
AbortError covers more than a cancelled dialog. The browser also raises it when it refuses a folder it considers sensitive, or when permission for the requested mode isn’t granted. So the handler above returns quietly rather than showing a “you cancelled” message.
List Entries and Open Subfolders
A FileSystemDirectoryHandle is an async iterable: for await (const entry of dir.values()) gives you each child, and each child is already a handle. Check entry.kind for 'file' or 'directory'. Iteration order isn’t guaranteed, so sort the results before you display them.
async function listNotes(dir) {
const notes = [];
for await (const entry of dir.values()) {
if (entry.kind === 'file' && entry.name.endsWith('.md')) notes.push(entry);
}
notes.sort((a, b) => a.name.localeCompare(b.name));
list.replaceChildren(...notes.map((h) => {
const li = document.createElement('li');
li.textContent = h.name;
li.onclick = () => openNote(h);
return li;
}));
}
To recurse, pass each directory entry straight back into the walker. To jump to a subfolder you already know the name of, use getDirectoryHandle(name):
async function* walk(dir, path = '') {
for await (const entry of dir.values()) {
if (entry.kind === 'directory') yield* walk(entry, `${path}${entry.name}/`);
else yield { handle: entry, path: path + entry.name };
}
}
const drafts = await notesDir.getDirectoryHandle('drafts');
Read a File With getFile()
Calling getFile() on a FileSystemFileHandle gives you a File, which is a Blob. Read text with .text() and binary data with .arrayBuffer(). If you know the file name, dir.getFileHandle('todo.md') skips the iteration step.
async function openNote(handle) {
const file = await handle.getFile();
editor.value = await file.text();
currentFile = handle;
}
The File is a snapshot. If another program changes the file afterwards, call getFile() again to see the new contents.
Write a File: Permission, createWritable, Close
To write a local file with the File System Access API, you need readwrite permission. Call createWritable() to get a stream, pass it strings, Blobs or buffers, then close it. Requesting mode: 'readwrite' in the picker gets the user’s consent up front, so the first save doesn’t need to ask.
saveBtn.addEventListener('click', async () => {
if (!currentFile) return; // no note open yet
saveBtn.disabled = true;
try {
const writable = await currentFile.createWritable();
await writable.write(editor.value);
await writable.close(); // contents reach disk here
} finally {
saveBtn.disabled = false;
}
});
Changes written to a FileSystemWritableFileStream reach the file on disk only when you call close(). Always await it. The handler keeps the Save button disabled until it resolves.
To create a new note, call notesDir.getFileHandle('new-note.md', { create: true }) and write to it the same way.
Remember the Folder Between Visits
You can store a FileSystemDirectoryHandle in IndexedDB and read it back on a later visit. Holding the handle doesn’t guarantee access, though, so check permission and ask again before you read or write. The MDN File System API overview notes that handles can be serialized to IndexedDB.
const db = () => new Promise((res, rej) => {
const r = indexedDB.open('notes-app', 1);
r.onupgradeneeded = () => r.result.createObjectStore('handles');
r.onsuccess = () => res(r.result);
r.onerror = () => rej(r.error);
});
async function saveHandle(h) {
const tx = (await db()).transaction('handles', 'readwrite');
tx.objectStore('handles').put(h, 'notesDir');
return new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); });
}
async function loadHandle() {
const req = (await db()).transaction('handles').objectStore('handles').get('notesDir');
return new Promise((res, rej) => { req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); });
}
Check access with queryPermission(). If it doesn’t return 'granted', ask with requestPermission(), which resolves to 'granted', 'denied' or 'prompt'. requestPermission() must be called from a user gesture, so trigger it from a button click, never on load.
async function ensureReadWrite(handle) {
const opts = { mode: 'readwrite' };
if ((await handle.queryPermission(opts)) === 'granted') return true;
return (await handle.requestPermission(opts)) === 'granted';
}
const saved = await loadHandle();
if (saved) {
reopenBtn.hidden = false;
reopenBtn.onclick = async () => {
if (await ensureReadWrite(saved)) { notesDir = saved; listNotes(saved); }
else { reopenBtn.hidden = true; openBtn.hidden = false; }
};
}
If permission is denied, the code shows the regular “Open folder” button again, and the user’s next click opens the picker. The Chrome 122 persistent permissions update lets users choose “Allow on every visit”, and installed apps keep the permission automatically. In other cases access may last only for the session, so always call queryPermission() before you use a stored handle.
Browser Support and the webkitdirectory Fallback
showDirectoryPicker() works in Chromium-based browsers: Chrome and Edge on desktop, and Chrome for Android from version 132. Firefox and Safari don’t support it, and MDN marks it Experimental with Limited availability. In those browsers, <input type="file" webkitdirectory> still reads a whole folder, and MDN lists it in every major browser (Chrome 7, Edge 13, Firefox 50, Safari 11.1). What you get is a read-only list of File objects, each with a webkitRelativePath, and no way to write back to the folder.
function pickFolderFallback() {
return new Promise((resolve) => {
const input = Object.assign(document.createElement('input'), { type: 'file', webkitdirectory: true });
input.addEventListener('change', () => resolve([...input.files].filter((f) => f.name.endsWith('.md'))));
input.addEventListener('cancel', () => resolve(null));
input.click();
});
}
function downloadNote(name, text) {
const url = URL.createObjectURL(new Blob([text], { type: 'text/markdown' }));
Object.assign(document.createElement('a'), { href: url, download: name }).click();
setTimeout(() => URL.revokeObjectURL(url), 0);
}
Listen for the input’s cancel event, or the Promise never settles. cancel also fires in place of change when the user selects the same folder again. On this path, Save means a download, as covered in creating a downloadable file in the browser. To let users drop files in as well, add the patterns from a custom file upload component with drag and drop.
showDirectoryPicker() | <input webkitdirectory> | OPFS | |
|---|---|---|---|
| User-visible folder | Yes | Yes | No, hidden by the browser |
| Read | Yes | Yes (snapshot) | Yes |
| Write back | Yes, with permission | No | Yes, no prompt |
| Survives reload | Handle in IndexedDB + permission check | No | Yes |
| Support | Chromium-based (Chrome, Edge, Chrome for Android) | All major browsers | See MDN |
Conclusion
Supporting real local folders comes down to four calls and one rule. Pick the folder from a click, iterate the handle, read with getFile(), and write through a stream that saves only on close(). Then store the handle in IndexedDB, and put the permission check behind a button so the user can reopen their folder on the next visit. Add the webkitdirectory fallback with download-to-save, test both paths over HTTPS, and your notes app will work in every major browser and write back to the folder wherever the API is supported.
FAQs
Does createWritable() overwrite the whole file or append to it?
It overwrites by default. createWritable() starts from an empty temporary file, so the data you write replaces the entire file when close() resolves. To keep the current contents, pass { keepExistingData: true }, which copies the existing file into the temporary file first. To append, call seek() with the file's current size before writing. The original file does not change until the stream is closed.
How do I delete a file or subfolder inside a folder opened with showDirectoryPicker()?
Call removeEntry(name) on the parent FileSystemDirectoryHandle, for example notesDir.removeEntry('old-note.md'). The handle needs readwrite permission, or the call throws NotAllowedError. Removing a folder that still has entries throws InvalidModificationError unless you pass { recursive: true }. If no entry with that name exists, it throws NotFoundError. Ask the user to confirm before deleting anything.
Can users drag a folder onto the page instead of using the picker?
Yes, in Chromium-based browsers. In the drop event handler, call getAsFileSystemHandle() on each DataTransferItem. A dropped folder resolves to a FileSystemDirectoryHandle, the same type that showDirectoryPicker() returns, so the same listing, reading and IndexedDB code works on it. Call it on every item before any await, because the handle is only available in the same tick as the drop event. Firefox and Safari do not support it.