Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท Native Modules and APIs

File System, Media Library and Sharing

Read and write files with expo-file-system, understand document and cache directories, download and upload files, pick documents, save to the photo library and share with expo-sharing.

Apps need to keep files: downloaded PDFs, photos from the camera, exported data, caches. Mobile operating systems sandbox apps, so each one gets private folders and cannot read other apps' files. Expo wraps the details in expo-file-system, and adds modules to pick documents, save to the photo library and share files with other apps.

The native modules are read-only code here (they need a device); live stand-ins implement an in-memory file system and path helpers so you can practice the logic.

Where files live

Each app sandbox has directories with different guarantees:

Directory Contents Survives app updates Can the OS delete it? Backed up
Document directory user data you want to keep yes no yes (iCloud/Google)
Cache directory downloads, thumbnails, temp files yes yes, when storage is low no
Bundle (read-only) your app's assets replaced on update no no

Rule of thumb: if you can re-create it by downloading again, it is a cache; if it is the user's work, store it in documents.

Two places for your files

Documents Keep. Backed up.
Cache Temporary. OS may clear it.
Sandbox Other apps cannot read it

Picker and camera results usually start in the cache.

1 / 2

The modern expo-file-system API

Recent SDKs provide an object API with File, Directory and Paths (the older functions like readAsStringAsync live in expo-file-system/legacy for existing code):

TSX
import { File, Directory, Paths } from 'expo-file-system';

// a file in the documents directory
const notes = new File(Paths.document, 'notes.txt');
notes.create({ overwrite: true });
notes.write('Pine Ridge: loved the larch forest.');
const text = await notes.text();          // read as a string
console.log(notes.exists, notes.size);

// a folder
const photos = new Directory(Paths.document, 'photos');
if (!photos.exists) photos.create();

// copy / move / delete
const cached = new File(Paths.cache, 'tmp.jpg');
cached.copy(photos);                       // copies into the folder
cached.delete();

// list a directory
for (const item of photos.list()) {
  console.log(item instanceof Directory ? 'dir ' : 'file', item.name);
}

Paths.document and Paths.cache are directories; Paths.join(...), Paths.basename() and Paths.extname() help with path strings. Method names and sync/async variants vary across SDK versions, so check the docs for the one you use; the concepts stay the same.

An in-memory file system

Modeling file operations is a good way to see the rules: paths, parents must exist, copy versus move, listing. This stand-in is not Expo code, but behaves similarly.

JS A tiny virtual file system

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Path helpers

Never build paths with string concatenation when you can avoid it; handle slashes and extensions in one place.

JS Safe filenames and extensions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Downloading and uploading

TSX
import { File, Paths } from 'expo-file-system';

// download to the cache (check your SDK docs for the exact helper)
const destination = new File(Paths.cache, 'trail-map.pdf');
const downloaded = await File.downloadFileAsync('https://example.com/trail-map.pdf', destination);
console.log(downloaded.uri, downloaded.size);

// upload with fetch and FormData
const body = new FormData();
body.append('photo', { uri: photoUri, name: 'photo.jpg', type: 'image/jpeg' } as any);
await fetch('https://api.example.com/photos', { method: 'POST', body });

Always check the HTTP status and handle failure: a 404 page can end up saved as "your PDF". Show progress for big transfers, and remember mobile users may be offline (Data, Storage and Networking).

Picking documents and saving media

TSX
import * as DocumentPicker from 'expo-document-picker';
import * as MediaLibrary from 'expo-media-library';

// let the user choose a file from Files / Drive
const res = await DocumentPicker.getDocumentAsync({ type: ['application/pdf', 'text/csv'], copyToCacheDirectory: true });
if (!res.canceled) console.log(res.assets[0].name, res.assets[0].size, res.assets[0].uri);

// save a photo to the system gallery (needs permission)
const perm = await MediaLibrary.requestPermissionsAsync(true);   // true = write only
if (perm.granted) await MediaLibrary.saveToLibraryAsync(photoUri);

The photo library is shared, user-owned storage, so it needs the permission flow from Camera and Image Picker and a purpose string (expo-media-library plugin option savePhotosPermission).

Sharing

expo-sharing opens the system share sheet for a file (share to Messages, Mail, Drive, AirDrop). It shares file URIs, so write the content to a file first:

TSX
import * as Sharing from 'expo-sharing';
import { File, Paths } from 'expo-file-system';

async function exportTrails(trails: unknown[]) {
  const file = new File(Paths.cache, 'trails.json');
  file.create({ overwrite: true });
  file.write(JSON.stringify(trails, null, 2));

  if (await Sharing.isAvailableAsync()) {
    await Sharing.shareAsync(file.uri, { mimeType: 'application/json', dialogTitle: 'Export trails' });
  }
}

For plain text or links, React Native's built-in Share.share({ message, url }) is enough. isAvailableAsync() returns false on some platforms (notably web), so guard it. expo-print can render HTML to a PDF file that you then share, and expo-clipboard handles copy and paste.

JS Build an export file

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the quoting of "Lake, North Shore" in CSV: a comma inside a field must be quoted.

Common mistakes

  • Saving user data in the cache directory and losing it when the OS clears it.
  • Forgetting that the parent folder must exist before writing.
  • Hard-coding absolute paths; they change between app installs and updates. Always start from Paths.document / Paths.cache (or store only the relative name).
  • Not checking the HTTP status before saving a download.
  • Sharing a content:// or temp URI that the target app cannot read; copy to the cache first.
  • Reading a huge file into a string at once.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should a user's saved notes be stored so the OS does not delete them?

    Documents are kept and backed up; the cache may be cleared when storage is low.
  2. 2. Why should you not hard-code absolute file paths?

    Build paths from Paths.document or Paths.cache at runtime instead.
  3. 3. What does Sharing.shareAsync expect?

    Write the content to a file first, then pass its URI.
  4. 4. What must you do before saving a photo to the user's gallery?

    The gallery is shared storage guarded by permissions.

Summary

  • Each app has a sandbox with a documents directory (keep) and a cache directory (disposable).
  • expo-file-system provides File, Directory and Paths to read, write, copy, move and list; build paths from the standard roots.
  • Pick files with expo-document-picker, save photos with expo-media-library, and share files with expo-sharing.
  • Check statuses and permissions, and keep large files out of memory.

Next: The Expo Modules API