1. 程式人生 > >React Native檔案讀寫操作

React Native檔案讀寫操作

最近公司專案要求進行定時上傳位置資訊,及埋點,因為使用的是RN開發,一開始就是想到在Android和Ios原生裡進行操作。
在原生裡面實現了定時任務,Android裡面使用的是broadcastReceive + service + timer實現了。
現在需要生成一個日誌檔案,一開始想在原生裡面進行實現檔案的讀寫。後來查詢相關資料,發現了一個不錯的第三方外掛,react-native-fs,現在記錄一下,整合步驟及簡單的檔案讀寫操作。
外掛地址:https://github.com/itinance/react-native-fs
自己寫了個Demo進行了測試,目前沒有什麼問題,Demo地址
https://github.com/wayne214/RNstudyDemo/blob/master/src/utils/readAndWriteFileUtil.js
1.整合
安裝命令:
npm install react-native-fs --save
//注意:如果react native版本是<0.40安裝,使用此標籤:
npm install

[email protected] --save
安裝後執行:
react-native link react-native-fs
Android新增相應許可權
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2.使用
匯入及設定檔案儲存路徑

![image.png](http://upload-images.jianshu.io/upload_images/3112038-fda4523e66b1db9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
讀寫操作

![image.png](http://upload-images.jianshu.io/upload_images/3112038-34dfe0b5fa0b414d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
刪除檔案

![image.png](http://upload-images.jianshu.io/upload_images/3112038-2b5e25ab7c8b55ec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
獲取檔案路徑

![image.png](http://upload-images.jianshu.io/upload_images/3112038-5fea9be6ec22fb3e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
判斷檔案路徑是否存在

![image.png](http://upload-images.jianshu.io/upload_images/3112038-3e45ae6309cb1289.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
拷貝檔案

![image.png](http://upload-images.jianshu.io/upload_images/3112038-f51d5334ef93ea74.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
建立目錄
/*建立目錄*/
    mkDir() {
        const options = {
            NSURLIsExcludedFromBackupKey: true, // iOS only
        };

        return RNFS.mkdir(destPath, options)
            .then((res) => {
                console.log('MKDIR success');

            }).catch((err) => {
                console.log('err', err);
            });
    }