Download txt file from text in React Native - react-native

I'm trying to Download txt file from a text but that function is not working fine.
Txt Function
import RNFS from 'react-native-fs';
const txtDownload = () => {
let path = `${RNFS.DocumentDirectoryPath}/${filename}.txt`;
RNFS.writeFile(path, `Here is text`, 'utf8').then((res) => {
Toast('File saved successfully');
}
).catch((err) => {
Toast(err);
});
}
It returns File saved successfully but I can't find file

Log the path and check the location where it's trying to store. For me, it shows the location as below when I try to store in ${RNFS.DocumentDirectoryPath}/help.txt
/data/user/0/com.sample/files/help.txt
I suspect you were checking in the Documents folder. I don't know if you can write to the Documents folder. But it works for the Download folder using RNFS.DownloadDirectoryPath.

Related

ReactNative read content of doc file

i'm trying to read the content of the doc file which is picked by a user to find a specific word in that document.
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.docx, DocumentPicker.types.doc],
});
i just want to read the content and find a specific word in that string from doc or docx file.
i have tried with react-native-fs to read at a specific address but it didn’t work in that way.
import RNFS from "react-native-fs";
RNFS.readFile(res.uri).then((data) => {
console.log(data);
})

How to copy file using expo filesystem

I am trying to create a simple whatsapp status downloader app for android using expo and I am using expo-file-system for copying file but I am unable to get the file anywhere.
My functions looks something like this :
export const saveFile = async (filePath) => {
const res = await FileSystem.copyAsync({
from: filePath,
to: `${FileSystem.documentDirectory}saved/test.mp4`,
});
};
where filepath uses SAF file path.

Process download file before save

import RNBackgroundDownloader from 'react-native-background-downloader';
let task = RNBackgroundDownloader.download({
id: 'file123',
url: 'https://link-to-very.large/file.zip'
destination: `${RNBackgroundDownloader.directories.documents}/file.zip`
}).begin((expectedBytes) => {
console.log(`Going to download ${expectedBytes} bytes!`);
}).progress((percent) => {
console.log(`Downloaded: ${percent * 100}%`);
}).done(() => {
console.log('Download is done!');
}).error((error) => {
console.log('Download canceled due to error: ', error);
});
// Pause the task
task.pause();
// Resume after pause
task.resume();
// Cancel the task
task.stop();
I am using the above code. In this i have problem that it downloads a file and save it as it. But i want to encode a file then save it in the internal directly of android folder. Let me know if anyone have a idea to do it. So that i can encode after that file will save.
Thanks
How about you download the file and then encode the local file and then save the encoded file and delete the original file.

React-native: download and unzip large language file

A multilingual react-native app. Each language bundle is ~50MB. It doesn't make sense to include all of them in a bundle. So, what do I do about it?
I assume the right way to go here is to download the respective language files upon language selection.
What do I do with it next? Do I suppose to store it using AsyncStorage or what?
Briefly explaining, you will:
Store JSON as ZIP in Google Storage (save memory/bandwidth/time)
Unzip file to JSON (in RN)
Store JSON in AsyncStorage (in RN)
Retrieve from AsyncStorage (in RN)
[Dependencies Summary] You can do this, using these deps:
react-native
react-native-async-storage
rn-fetch-blob
react-native-zip-archive
Tip: Always store big language json in zip format (this can save up to 90% of size).
I made a quick test here: one 3.52MB json file, turned out a 26KB zipped file!
Let's consider that yours stored zip file, can be accessed by using a public url, eg: https://storage.googleapis.com/bucket/folder/lang-file.zip.
Install and link all above RN deps, it's required to get this working.
Import the deps
import RNFetchBlob from 'rn-fetch-blob';
import { unzip } from 'react-native-zip-archive';
import AsyncStorage from '#react-native-community/async-storage';
Download the file using rn-fetch-blob. This can be done using:
RNFetchBlob
.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
//some headers ..
})
.then((res) => {
// the temp file path
console.log('The file saved to ', res.path())
// Unzip will be called here!
unzipDownloadFile(res.path(), (jsonFilePath) => {
// Let's store this json.
storeJSONtoAsyncStorage(jsonFilePath);
// Done!
// Now you can read the AsyncStorage everytime you need (using function bellow).
});
});
[function] Unzip the downloaded file, using react-native-zip-archive:
function unzipDownloadFile(target, cb) {
const targetPath = target;
const sourcePath = `${target}.json`;
const charset = 'UTF-8';
unzip(sourcePath, targetPath, charset)
.then((path) => {
console.log(`unzip completed at ${path}`)
return cb(path);
})
.catch((error) => {
console.error(error)
});
}
[function] Store JSON in AsyncStorage:
function storeJSONtoAsyncStorage (path) {
RNFetchBlob.fs.readFile(path, 'utf-8')
.then((data) => {
AsyncStorage.setItem('myJSON', data);
});
}
Retrieve JSON data from AsyncStorage (everytime you want):
AsyncStorage.getItem('myJSON', (err, json) => {
if (err) {
console.log(err);
} else {
const myJSON = JSON.parse(json);
// ... do what you need with you json lang file here...
}
})
That's enough to get dynamic json lang files working in React Native.
I'm using this approach to give a similar feature to my i18n'ed project.
Yes you are right to make the translation file downloadable.
You can store the downloaded file in the document directory of your app.
After that you can use a package to load the translations. For instance
https://github.com/fnando/i18n-js.
I would also suggest taking a look at the i18n library which is a standard tool for internationalisation in JavaScript.
Consider taking a look at this documentations page where you can find an option of loading a translation bundle or setting up a backend provider and hooking into it.
Also, to answer the storage question, if you do not plan on setting up a backend: AsyncStorage would be an appropriate place to store your key - translation text pairs.

How to upload files from file manager without using iCloud?

I want to upload doc and pdf files from my React Native app. I used React Native document picker but it works with iCloud and I want to select files from the file manager.
Here is my code:
import { DocumentPicker, DocumentPickerUtil } from 'react-native-document-picker';
selectFile(type,index='') {
DocumentPicker.show({
filetype: [DocumentPickerUtil.allFiles()],
},(error,res) => {
console.log(
res.uri,
res.type, // mime type
res.fileName,
res.fileSize
);
});
}