Expo项目读写根目录JSON文件遇问题,求解决方案及目录区别
问题:Expo中使用expo-file-system读写同目录JSON文件失败
我正尝试通过expo-file-system访问与App.js同目录的JSON文件以进行读写操作,但始终无法成功。当前使用的Expo版本为51.0.38,项目目录结构中myData.json与App.js处于同一层级。
尝试1:使用FileSystem.bundleDirectory拼接路径
代码实现:
import * as FileSystem from "expo-file-system" // ...其他代码 const JSONPath = FileSystem.bundleDirectory + "myData.json"; console.log(JSONPath); // 输出 asset:/myData.json FileSystem.readAsStringAsync(JSONPath).then(res => { console.log(JSON.stringify(res)); // 控制台无输出 });
抛出异常:
Console Warning: Possible unhandled promise rejection (id: 2): Error: Call to function 'ExponentFileSystem.readAsStringAsync' has been rejected. -> Caused by: java.io.FileNotFoundException: myData.json
尝试2:使用FileSystem.documentDirectory拼接路径
代码实现:
import * as FileSystem from "expo-file-system" // ...其他代码 const JSONPath = FileSystem.documentDirectory + "myData.json"; console.log(JSONPath); // 输出 file:///data/user/0/host.exp.exponent/files/myData.json FileSystem.readAsStringAsync(JSONPath).then(res => { console.log(JSON.stringify(res)); // 控制台无输出 });
抛出异常:
Console Warning: Possible unhandled promise rejection (id: 3): Error: Call to function 'ExponentFileSystem.readAsStringAsync' has been rejected. -> Caused by: java.io.FileNotFoundException: /data/user/0/host.exp.exponent/files/myData.json (No such file or directory)
其他尝试
尝试使用@expo/json-file工具,但该工具因依赖fs模块与Expo不兼容而报错。
求助问题
- 如何成功实现
App.js同目录JSON文件的读写操作? documentDirectory与bundleDirectory的区别是什么?
内容的提问来源于stack exchange,提问作者HASAN KHADDAM
相关产品推荐
相关产品推荐

