如何在 React Native 中备份/恢复 SQLite 数据库

Vin*_*k B 5 sqlite react-native react-native-android react-native-ios

我正在使用andpor/react-native-sqlite-storage在 React Native 中管理 SQLite 数据库。现在我想将我的所有数据库备份到一个加密文件中,然后在以后恢复它。我知道如何在 android 中做到这一点,但不知道如何在 react native 中实现这一点。

如果它在android中,下面的代码可以帮助我在不加密的情况下备份数据库。

 final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);

String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";

// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);

// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
    output.write(buffer, 0, length);
}

// Close the streams
output.flush();
output.close();
fis.close();
Run Code Online (Sandbox Code Playgroud)

所以我的问题是如何在 React Native 上做到这一点。如果有任何可用的库,请向我建议。

小智 4

使用react-native-fs包在react-native中也可以遵循相同的方法。

import RNFS from 'react-native-fs';

RNFS.readFile("/data/data/<your.app.package>/databases/foo.db", "base64")
    .then(value => RNFS
        .getAllExternalFilesDirs()
        .then(path => RNFS.writeFile(path + "/" + "database_copy.db", value, "base64"))
        .then(() => console.log("Successful"))
    )

Run Code Online (Sandbox Code Playgroud)