Lesson 22 / 30
File System API
Open, edit and save local files with the File System Access API, and feature-detect it for limited browser support.
File access with user consent
The File System Access API lets your app open, read and write files on the user's device with explicit permission. Support is limited to Chromium browsers, so provide a fallback such as a file input and download link.
Open and read files
Use showOpenFilePicker to access user files.
const openFileBtn = document.getElementById('open-file');
openFileBtn.addEventListener('click', async () => {
try {
const [fileHandle] = await window.showOpenFilePicker({
types: [{ description: 'Text files', accept: { 'text/plain': ['.txt'] } }]
});
const file = await fileHandle.getFile();
const content = await file.text();
console.log('File content:', content);
} catch (err) {
console.error('File picker error:', err);
}
});
Output:
User can select files; app reads and processes them directly.