Lesson 21 / 29

File System API

Access and manipulate files on the device using the File System Access API.

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. Users can pick files, and your app works with them directly.

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.