Member-only story
Export To The File System (Save As…) + Fallback In TypeScript
How to save a file to the user’s local devices with the new File System Access API and a fallback for incompatible browsers.

In almost every web application I end up reusing the same pattern to export data to the file system in JavaScript — i.e. a solution that uses the File System Access API and a good old “download” feature as fallback. I thought it was worth writing a post about it as documentation purpose 😉.
Introduction
The File System Access API allows read, write and file management capabilities within your browser. It enables developers to build powerful web apps that interact with files on the user’s local device.
The web.dev team has a tutorial that introduces and highlights all the features.
It is a relatively new API and therefore is not yet adopted by all browser vendors.
For example, one of the key feature we are about the use — showSaveFilePicker
which opens a dialog to select the destination of the file that will be written on user’s local drive — is only supported by Edge, Chrome and Opera (Feb. 2022- source Caniuse).
Getting Started
Generally speaking I use TypeScript. This solution is provided with type safety as well. That’s why it needs first the installation of the type definitions for the File System Access API.
npm i -D @types/wicg-file-system-access
Hands-on
To export file I use a Blob
— i.e. the content of the file I want to export — and a filename
. I create a single function that saves to the user’s local device and that can be use across my app.
export const save = (data: {blob: Blob, filename: string}) => {
if ('showSaveFilePicker' in window) {
return exportNativeFileSystem(data);
}
return download(data);
};
File System Access API — Save As
Above feature tests if showSaveFilePicker
is available in the window
object — i.e. it checks if the browser supports the File System…