react-native-fs 使用小demo

前言

最近在學習react-native,須要讀取文件,用了react-native-fs這個庫,記錄一下.
其實使用方式文檔上已經寫得很清楚了,這裏就介紹一下我本身是怎麼使用,廢話很少說,請看代碼:react

// file.js
import RNFS from 'react-native-fs';
import moment from 'moment';
import { Platform } from 'react-native';

// 文件路徑
const defaultPath = (Platform.OS === 'ios' ? RNFS.MainBundlePath : RNFS.DocumentDirectoryPath) + '/data'; 
const destPath = defaultPath + '/test';
const splitStr = '20191115###';

class FileUtil {
    async writeFile(data, filename) {
        const isDir = await this.mkDir();
        // console.log(isDir, 'dir')
        if (!isDir) {
            return false;
        }

        // data.createTime = +new Date();
        const jsonStr = JSON.stringify(Object.assign({}, data, { createTime: +new Date() }));
        // const today = moment().startOf('day').valueOf();
        let filePath = defaultPath + '/';
        if (filename) {
            filePath += filename;
        } else {
            const today = moment().valueOf();
            filePath += today + '.txt';
        }
        
        // 判斷文件是否存在
        const isExists = await this.isExistFile(filePath);
        if (!isExists) {
            return await RNFS.writeFile(filePath, jsonStr, 'utf8')
            .then((success) => {
                console.log('FILE WRITTEN!');
                return success;
            })
            .catch((err) => {
                console.log(err.message);
            })
        } else {
            return await this.appendFile(jsonStr, filePath);
        }
    }
    // 向文件中添加內容
    async appendFile(data, path) {
        const jsonStr = JSON.stringify(data);
        return await RNFS.appendFile(path, splitStr + jsonStr, 'utf8')
            .then((success) => {
                console.log('FILE APPEND SUCCESS');
                return success;
            })
            .catch((err) => {
                console.log(err.message);
            });
    }

    // 判斷文件是否存在
    isExistFile = async (filePath, cb) => {
        return await RNFS.exists(filePath)
            .then(res => {
                console.log('isExists, ' + res)
                cb && cb(res);
                return res;
            });
    };

    // 讀取文件
    async readFile(filePath,name, successCallback, failCallback) {
        const isExists = await this.isExistFile(filePath);
        if (!isExists) return;

        return await RNFS.readFile(filePath, 'utf8')
            .then((result) => {
                // Alert.alert(result)
                // console.log('=================file read start===================')
                const res = result.indexOf(splitStr) > -1 ? result.split(splitStr) : [result];

                // console.log(res)
                // console.log('=================file read end===================')
                // console.log(res.length, JSON.parse(res[0], 'ppppp'))
                for (let i = 0, len = res.length; i < len; i++) {
                    res[i] = JSON.parse(res[i]);
                }
                // console.log(res[2])

                successCallback && successCallback(result);
                return {
                    name,
                    content: res,
                };
            })
            .catch((err) => {
                failCallback && failCallback(err.message)
            });
    }

    async editFile(name, data) {
        // 先刪除文件,再建立
        const filePath = defaultPath + '/' + name;
        console.log(filePath, 'filePath edit')
        const isExists = await this.isExistFile(filePath);
        console.log('edit file exists is,', isExists);

        await this.deleteFile(filePath);

        // 寫入文件
        return await this.writeFile(data.join(''), name);
    }

    // 讀取目錄
    async readDir() {
        // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
        const res = await RNFS.readDir(defaultPath) 
            .then((result) => {

                const resP = [];
                if (result && result.length > 0) {
                    result = result.filter(item => item.isFile());
                    for (let i = 0, len = result.length; i < len; i++) {
                        // resP[i] = RNFS.readFile(result[i].path, 'utf8')
                        resP[i] = this.readFile(result[i].path, result[i].name);
                    }
                }
                return Promise.all(resP);
            })
            .then((statResult) => {
                return statResult;
            })
            .catch((err) => {
                console.log(err.message, err.code);
            });

        console.log('+++++++++++++++++++++++++++++++++++++++++++++++++++')
        console.log(res, 'end of read')
        return res;
    }

    // 讀取目錄
    readDir1() {
        RNFS.readDir(defaultPath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
            .then((result) => {
                console.log('GOT RESULT', result);
                console.log('++++++++++++++++++++++++++++++++++++++++')
                console.log(result.length)
                console.log('================================================')

                // stat the first file
                return Promise.all([RNFS.stat(result[0].path), result[0].path]);
            })
            .then((statResult) => {
                console.log(statResult)
                if (statResult[0].isFile()) {
                    // if we have a file, read it
                    return RNFS.readFile(statResult[1], 'utf8');
                }

                return 'no file';
            })
            .then((contents) => {
                // log the file contents
                console.log('=======================================================')
                console.log(contents, 'content');
            })
            .catch((err) => {
                console.log(err.message, err.code);
            });
    }
    // 刪除文件
    async deleteFile(filePath) {
        const path = filePath || defaultPath;
        const res = await RNFS.unlink(path)
            .then(() => {
                console.log('FILE DELETED');
            })
            .catch((err) => {
                console.log(err.message);
            })
        return res;
    }
    getPath() {
        return 'file://'.concat(destPath);
    }
    // 判斷文件路徑是否存在
    isFilePathExists(successCallback) {
        RNFS.exists(destPath)
            .then((value) => {
                successCallback(value);
            })
            .catch((err) => {
                console.log(err.message);
            });
    }
    // 複製文件
    copyFile() {
        RNFS.copyFile(defaultPath, destPath)
            .then(() => {
                console.log('COPY FILE SUCCESSED');
            })
            .catch((err) => {
                console.log('copyFile Failed', err.message);
            });

    }
    // 移動文件
    moveFile() {
        RNFS.moveFile(defaultPath, destPath)
            .then(() => {
                console.log('moveFIle Success');
            })
            .catch((err) => {
                console.log('moveFile failed', err);
            });
    }
    /*建立目錄*/
    async mkDir() {
        const options = {
            NSURLIsExcludedFromBackupKey: true, // iOS only
        };

        return await RNFS.mkdir(defaultPath, options)
            .then((res) => {
                console.log('MKDIR success', res);
                return true;
            }).catch((err) => {
                console.log('err', err);
            });
    }
}

const instance = new FileUtil();

export default instance;

使用方式:ios

// home.js

import FileUtil from '../../utils/file';
...
<Button
                    title="write"
                    onPress={async () => {
                        const res1 = FileUtil.writeFile({ time: +new Date(), money: (Math.random() * 100).toFixed(2), category: [1, 2] });
                        // console.log(1111111111)
                        const res = await FileUtil.readDir();
                        Alert.alert(JSON.stringify(res))
                    }}
                />
                <Button
                    title="read"
                    onPress={() => FileUtil.readFile()}
                />
                <Button
                    title="read Dir"
                    onPress={async () => {
                        Alert.alert(3)
                        const res = await FileUtil.readDir();
                        Alert.alert(JSON.stringify(res))
                    }
                    }
                />
                <Button
                    title="delate Dir a"
                    onPress={() => FileUtil.deleteFile()}
                />

參考連接:
react-native-fs API Documentgit

廣告時間

歡迎跟我一塊兒挖坑、填坑、扯淡。哈哈哈
qrcode_for_gh_1961e601cc53_258.jpggithub

相關文章
相關標籤/搜索