More posts

Using the JavaScript filesystem API

29 March, 2024

Here’s how to open a file

const [fileHandle] = await window.showOpenFilePicker();
    
const file = await fileHandle.getFile();
const contents = await file.text();

Here’s how to save a file

const options: SaveFilePickerOptions = {
  types: [
    {
      description: 'Markdown',
      accept: {
        'text/plain': ['.md'],
      },
    },
  ],
};

const handle = await window.showSaveFilePicker(options);

To write to a file you already have “open” you need to create a writable stream. fileHandle is the variable from above.

const writableStream = await fileHandle.createWritable();
await writableStream.write(fileContent);
await writableStream.close();