File system access lets your app read and write files on the device. This helps save user data or load files anytime.
0
0
File system access in React Native
Introduction
Saving user settings or preferences locally
Downloading and storing images or documents
Reading a saved text file to show content
Caching data to improve app speed
Logging app events for debugging
Syntax
React Native
import RNFS from 'react-native-fs'; // Write a file RNFS.writeFile(path, contents, 'utf8') .then(() => console.log('File written')) .catch(err => console.log(err)); // Read a file RNFS.readFile(path, 'utf8') .then(contents => console.log(contents)) .catch(err => console.log(err));
Use react-native-fs library for file system operations in React Native.
Always handle errors to avoid app crashes.
Examples
This example saves a text file named
test.txt with a simple message.React Native
const path = RNFS.DocumentDirectoryPath + '/test.txt'; const content = 'Hello from React Native!'; RNFS.writeFile(path, content, 'utf8') .then(() => console.log('File saved')) .catch(err => console.log(err));
This reads the previously saved file and logs its content.
React Native
RNFS.readFile(RNFS.DocumentDirectoryPath + '/test.txt', 'utf8') .then(contents => console.log('File content:', contents)) .catch(err => console.log(err));
Sample App
This React Native component has two buttons: one to save a file with a message, and one to read that file and show its content below.
React Native
import React, { useState } from 'react'; import { View, Text, Button, Alert } from 'react-native'; import RNFS from 'react-native-fs'; export default function FileExample() { const [fileContent, setFileContent] = useState(''); const path = RNFS.DocumentDirectoryPath + '/hello.txt'; const saveFile = () => { RNFS.writeFile(path, 'Hello React Native!', 'utf8') .then(() => Alert.alert('File saved')) .catch(err => Alert.alert('Error: ' + err.message)); }; const readFile = () => { RNFS.readFile(path, 'utf8') .then(contents => setFileContent(contents)) .catch(err => Alert.alert('Error: ' + err.message)); }; return ( <View style={{ padding: 20 }}> <Button title="Save File" onPress={saveFile} /> <Button title="Read File" onPress={readFile} /> <Text style={{ marginTop: 20, fontSize: 16 }}>Content: {fileContent}</Text> </View> ); }
OutputSuccess
Important Notes
File paths differ by platform; use RNFS.DocumentDirectoryPath for safe storage.
Always ask for permissions if your app needs to access external storage on Android.
Test file operations on real devices as simulators may behave differently.
Summary
File system access lets apps save and load files on the device.
Use react-native-fs for easy file reading and writing.
Handle errors and permissions carefully for smooth user experience.