1

Below is my code to read a JSON file which is already downloaded and stored in "TemporaryDirectoryPath".

var fileName = getFileNameFromUrl(url); RNFS.downloadFile({ fromUrl: url, toFile: `${RNFS.TemporaryDirectoryPath}/`+fileName }).promise.then(r => { var content = RNFS.readFile(`${RNFS.TemporaryDirectoryPath}/`+fileName, 'utf8'); console.log(content); }); 

I am getting an object of type "Promise" as below

Promise {_40: 0, _65: 0, _55: null, _72: null} _40: 0 _55: "{"show_explanation":1,"answer_result":2, //More json content will be here}" _65: 1 _72: null 

How to read content from that Promise object?

2

3 Answers 3

2

Why dont you just import it with "import"

import AnyName from './pathToYourJSONfile'; 

I have to write here, low rep for adding comments! :/

Sign up to request clarification or add additional context in comments.

10 Comments

The file is getting downloaded and storing the file name in the local DB, and later I have to read the file content and display. So I don't know what is the filename to import, and there can be multiple files which I may need to download.
wait ...1st you download this json file from some server and save its name to db ? ...and than you need to import it to your app ?
I am not importing. I have to read the content of the file which I am downloading from an URL. I updated the code, please refer.
Do you know whats in that file ? and will it always be the same content?
No, content will be different. But the content structure will be same. And it's not about a single file, I need to download multiple files. and the number of files to download also not a constant.
|
0

You already know RNFS.readFile() return Promise.

So you just need to learn how to use Promise.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

var fileName = getFileNameFromUrl(url); RNFS.downloadFile({ fromUrl: url, toFile: `${RNFS.TemporaryDirectoryPath}/` + fileName }) .then(r => { RNFS.readFile(`${RNFS.TemporaryDirectoryPath}/` + fileName, 'utf8') .then(content => { console.log(content); }) }); 

1 Comment

I tried your suggestion, but still the output is: ` { _40: 0, _65: 0, _55: null, _72: null }`
0

I had the same problem and managed to finally get the content with following snipped:

let asset_content = null; try { await RNFetchBlob.fs.readFile(assetFile_path, 'utf8') .then((data) => { asset_content = data; console.log("got data: ", data); }) .catch((e) => { console.error("got error: ", e); }) } catch (err) { console.log('ERROR:', err); } const assets = JSON.parse(asset_content); 

You might also have to ensure that the content has been saved as 'utf8'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.