Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to backup/restore SQLite database in React native

I am using andpor/react-native-sqlite-storage for managing SQLite database in React native. Now I want to backup all my database into a encrypted file then restore this at later time. I know how to do this in android but don't know how to implement this in react native.

if it is in android below code can help me to backup the database without encryption.

 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();

So my question is how I can do this on React Native. If there any libraries available please suggest to me.

like image 574
Vinayak B Avatar asked Jun 18 '18 06:06

Vinayak B


1 Answers

Same approach can be followed in react-native too using react-native-fs package.

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"))
    )

like image 70
shakil ruet Avatar answered Oct 13 '22 01:10

shakil ruet