安装模块
npm install react-native-fs --save
写入文件
import RNFS from 'react-native-fs';
const filePath = RNFS.DocumentDirectoryPath + '/example.json';
const jsonData = { key: 'value' };
const jsonString = JSON.stringify(jsonData);
RNFS.writeFile(filePath, jsonString, 'utf8')
.then(() => {
console.log('JSON data has been written to the file.');
})
.catch((error) => {
console.error('Error writing to the JSON file:', error);
});
读取文件
import RNFS from 'react-native-fs';
const filePath = RNFS.DocumentDirectoryPath + '/example.json';
RNFS.readFile(filePath, 'utf8')
.then((fileContent) => {
const jsonData = JSON.parse(fileContent);
console.log('JSON Data:', jsonData);
})
.catch((error) => {
console.error('Error reading the JSON file:', error);
});