Cordova Sample: Reading a text file

This post is more than 2 years old.

A few weeks back I began a list of questions to help build a PhoneGap/Cordova File System FAQ. (More on that at the very end.) As I work through the questions I'm building little samples (like this one) to help demonstrate various FileSystem features. Today's is really simple, but as always, I figure people can find this helpful even if it trivial. (And if I'm wrong, let me know in the comments below.) Today's example simply reads a text-based file from the file system and displays it in the application.

Let's take a look at the code and then I'll walk you through what it does.

document.addEventListener("deviceready", init, false);
function init() {
	
	//This alias is a read-only pointer to the app itself
	window.resolveLocalFileSystemURL(cordova.file.applicationDirectory + "www/index.html", gotFile, fail);

	/* Yes, this works too for our specific example...
	$.get("index.html", function(res) {
		console.log("index.html", res);
	});
	*/

}

function fail(e) {
	console.log("FileSystem Error");
	console.dir(e);
}

function gotFile(fileEntry) {

	fileEntry.file(function(file) {
		var reader = new FileReader();

		reader.onloadend = function(e) {
			console.log("Text is: "+this.result);
			document.querySelector("#textArea").innerHTML = this.result;
		}

		reader.readAsText(file);
	});

}

After deviceready fires, we use resolveLocalFileSystemURL to translate a path into a FileEntry object. Once again I'm using one of the aliases that ship with the latest version of the File plugin: cordova.file.applicationDirectory. As you can probably guess, this points to the application itself and is read-only, which is fine for our purposes. To this path I add www/index.html to refer to the index.html of the app itself.

As you can see in the commented out code, if I really did want to read something inside the www folder, I could just use Ajax. The example in the comment is jQuery-based. But since I wanted to demonstrate the FileSystem API I use it instead. For something this simple I'd probably just use Ajax typically.

Once we get the FileEntry object we can then run the file method on it. This gives us a handler to the file itself (think of FileEntry as the agent for the movie star file that is too busy to give us the time of day). Once we have that, we then fire up a new FileReader object, run readAsText on it, and wait for the read operation to end. Once it is done we have access to the contents of the file and can do - whatever - with it. In the sample app I simply added a text area to the DOM.

That's it. Full source may be found here: https://github.com/cfjedimaster/Cordova-Examples/tree/master/readtextfile.

As a quick FYI, I have begun work on the FAQ itself. You can view (and comment) on the Google doc here: https://docs.google.com/document/d/1qKB63z3U2BwCl7Gc-Ry7cPbNbQB-Cur2BaS1BRB1tV0/edit?usp=sharing

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Martin Cisneros Capistrán posted on 7/16/2014 at 2:00 AM

Hi Raymond i have a question i don't know if this is the best place to do it but... wel... can you tell me why the examples of phonegap/cordova plugins at github are shorter than the examples of phonegap 3.3.0 ? An example:

The Camera Plugin at github (phonegap greater than 3.3.0 version):
https://github.com/apache/c...

The Camera Plugin Examples (phonegap 3.3.0):
http://docs.phonegap.com/en...

Just why? :/

Comment 2 by Martin Cisneros Capistrán posted on 7/16/2014 at 2:01 AM

Sorry the second link is

http://docs.phonegap.com/en...

Comment 3 by Martin Cisneros Capistrán posted on 7/16/2014 at 2:03 AM

I can't post the original link hehe:

http://docs.phonegap.com/en...

Comment 4 by anchal arora posted on 7/16/2014 at 1:48 PM

I am getting an error
uncaught TypeError :
cannot read property 'application directory' of undefined
can u please help me..

Comment 5 by Raymond Camden posted on 7/16/2014 at 7:07 PM

@Martin: Um, I think because PG is still using internal docs, where on Cordova they always link to the plugin docs itself, which is, imo, more "proper".

@anchal: Ensure you added the plugin as described in the readme.md.

Comment 6 by Martin Cisneros Capistrán posted on 7/16/2014 at 9:37 PM

Oh i see, thank you!

Comment 7 by Rob Posener posted on 8/6/2014 at 11:10 AM

The HTML5Rocks web site that is referenced throughout the Cordova documentation now says:
“In April 2014, it was announced on public-webapps that the Filesystem API spec should be considered dead. Other browsers have showed little interest in implementing it.”
What is the Codova development team’s position on this?
Are they likely to change the API?
I'm concerned that I might put some considerable effort into this API (like I did before the file feature API was completely changed when it was made a plugin) and then find that it needs to be changed yet again.

Comment 8 by Raymond Camden posted on 8/6/2014 at 4:00 PM

One thing to keep in mind is that - obviously - even if Cordova 4.0 removes FS support your app will not all of a sudden stop working.

The best thing I can suggest is for you to post your concerns to the Cordova mailing list. That's a direct line to the people working on Cordova.

In my opinion, the FS stuff will never be removed, even though it may be dead as a spec on desktop. It is just too important for apps.

Comment 9 by Rob Posener posted on 8/6/2014 at 11:13 PM

Thanks for that insight Raymond.

Comment 10 by Jim Andrews posted on 8/19/2014 at 2:29 AM

Ya I'm getting an error on your code also. Running Android. I did add the plugin to Cordova properly via
cordova plugin add org.apache.cordova.file

Did you check the code when running Android?

Comment 11 by Raymond Camden posted on 8/19/2014 at 2:45 AM

I believe it is this issue: https://issues.apache.org/j...

It came up from an issue on my repo: https://github.com/cfjedima...

Comment 12 by F. Stephen Kirschbaum posted on 10/17/2014 at 12:09 AM

Raymond,

This is handy, but I'm struggling to find good practical examples going the other direction and WRITING files.

Essentially, I want to be able to store a few files to the cordova.file.applicationStorageDirectory to keep them persistent in the app and I'm not seeing exactly how to implement that with all the conflicting spec information out there.

Can you point me in the right direction?

Comment 13 by Raymond Camden posted on 10/17/2014 at 9:06 PM

Until I get time to make a little demo like the one here, the best I can suggest is the docs.

Comment 14 by F. Stephen Kirschbaum posted on 10/17/2014 at 9:19 PM

Thanks anyway! I'm working my way through the docs, they are just not super clear on 'interaction' as it were. It's great that I know how to read a file from some where. I know how to write a file to somewhere, but gee golly if I can get them to all work together at the same time... well that'd be just dandy!

Anyway, I'm actually making progress regardless, but thanks for your response!

Comment 15 by Rajesh posted on 11/14/2014 at 9:52 PM

Hi Raymond,
thanks for the example here.
I am still facing that issue of android where im gettting "file Not found" with this example.

But what i am really interested in is for ANDROID, reading and writing files to/from the cordova.file.applicationStorageDirectory.

Did you come up with an example for the same ?
If yes, please share the same with us.

thanks,
Rajesh

Comment 16 by Raymond Camden posted on 11/14/2014 at 9:54 PM

Did you see my blog post on downloading assets? Not the same directory, but very similar.

http://www.raymondcamden.co...

Comment 17 by Rajesh posted on 11/15/2014 at 7:23 PM

thanks Raymond, your example gave me an idea about the path to the applicationStorageDirectory.

But when the file is not present how to create a file ?

for ex:
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "/path/to/file/sampleFile.txt", gotFile, fail);

here the above file "sampleFile.txt" doesnt exist. How to create the file when it doesnt exist ?

Comment 18 by Raymond Camden posted on 11/15/2014 at 7:33 PM
Comment 19 by Rajesh posted on 11/15/2014 at 7:39 PM

thanks a lot raymond especially for your quick response :)

Comment 20 by sawyer posted on 1/13/2015 at 8:33 AM

Hi Raymond , i got a question when i run ur demo,the eclipse reports FileNotFoundException ,i don know why ,is there any problem in my config.xml?

Comment 21 (In reply to #20) by Raymond Camden posted on 1/13/2015 at 3:07 PM

Unfortunately this code is broken on Android due to this bug: https://issues.apache.org/j...

For now, if your code is really under www as it is in my demo, use XHR.

Comment 22 (In reply to #21) by sawyer posted on 1/14/2015 at 9:47 AM

this approach works out .Thks a lot ! but what if i want to write something into the txt, what sould i do ?

Comment 23 (In reply to #22) by Raymond Camden posted on 1/14/2015 at 12:30 PM

Search the blog - I also have demos for writing. :) Or you can go to my GitHub repo where I store all of them: https://github.com/cfjedima...

(To be clear, that repo doesn't have *all* my demos - I started using it about a year ago to have a central place, but I've been blogging about PhoneGap/Cordova longer than that.)

Comment 24 (In reply to #4) by GillesCa posted on 8/21/2015 at 9:13 AM

you need to add the file plugin.

Go to your applications directory via CMD (windows). And typ the following command: cordova plugin add cordova-plugin-file

With the assumption you installed the cordova CLI.
More info Cordova CLI: https://cordova.apache.org/...
More info file plugin: https://github.com/apache/c...

Comment 25 by Realtebo posted on 12/4/2015 at 1:32 PM

After I've done npm install cordova-plugin-file which.js file must I include to be able to use the plugin in my Cordova app?

Comment 26 (In reply to #25) by Raymond Camden posted on 12/4/2015 at 1:49 PM

Don't. Do cordova plugin add cordova-plugin-file.

Comment 27 by mohammad raza posted on 4/1/2016 at 6:22 AM

Thanks for a very nice tutorial.
I've implemented read/write file functionality. My question is, how can I know that whether the file exist or not. And if it do not exist, so I would create a new one...

Comment 28 (In reply to #27) by Raymond Camden posted on 4/2/2016 at 2:23 PM

I'd check the docs on the FileSystem API (Chrome's older docs), but I believe you can make a new File object on the path and check the properties there. Definitely doable. Or - do a Directory object on the parent and get a list of files.

Comment 29 (In reply to #28) by mohammad raza posted on 4/4/2016 at 11:42 AM

Right. I'll test it. Thanks

Comment 30 by AbdAllah posted on 8/9/2016 at 3:39 PM

dude, simply you rock!

Comment 31 (In reply to #30) by Raymond Camden posted on 8/9/2016 at 3:41 PM

Thank you.

Comment 32 by Pier posted on 8/18/2016 at 4:50 PM

You are a life saver man!

Comment 33 by mrityunjay mathapati posted on 9/22/2016 at 4:47 PM

Very informative.....a small query ..I have an external db file kept at www/example.db and Now I want it to move to root directory app/data/data/{app_package}/databases then how can I achieve ...Thanks in advance

Comment 34 (In reply to #33) by Raymond Camden posted on 9/22/2016 at 5:59 PM

Go to the docs for the File plugin and they link to an article talking about how to do stuff w/ the File system, including move operations.

Comment 35 (In reply to #34) by mrityunjay mathapati posted on 9/22/2016 at 6:06 PM

Thank you .!!

Comment 36 by Web Expert posted on 10/13/2016 at 5:35 AM

Is there any way to read file from external SD Card?
Thanks

Comment 37 (In reply to #36) by Raymond Camden posted on 10/13/2016 at 11:50 AM

Check the File plugin docs and look at the 'externalStorageDirectory' values.

Comment 38 (In reply to #37) by Web Expert posted on 10/13/2016 at 11:59 AM

Please make sure externalStorageDirectory value is exist
I can't find that value.

Comment 39 (In reply to #38) by Raymond Camden posted on 10/13/2016 at 12:07 PM

Did you install the plugin? Did you read the docs? It isn't "just" externalStorageDirectory, it is cordova.file.externalDataDirectory or externalApplicationStorageDirectory. I typoed above - but again - read the docs for more information on the alias.

Comment 40 (In reply to #39) by Web Expert posted on 10/13/2016 at 12:10 PM

Sure, I tried all APIs , but didn't get external SD card(I inserted micro card), only got android's internal memory.

Comment 41 (In reply to #40) by Raymond Camden posted on 10/13/2016 at 12:18 PM

Not sure what to suggest then. Sorry.

Comment 42 by sribharanidharan posted on 11/24/2016 at 8:40 AM

Thanks for the simple code. i'm getting error {code:1}. can you please tell me why i'm getting this error

Comment 43 (In reply to #42) by Raymond Camden posted on 11/24/2016 at 4:46 PM

If you check the docs, https://www.npmjs.com/packa..., you will see a list of error codes, and that one is listed.

Comment 44 by Jack posted on 12/7/2016 at 11:04 AM

i am new in this framework so asking may be the stupid question but where to copy this code ?? means in which file. ?

Comment 45 (In reply to #44) by Raymond Camden posted on 12/7/2016 at 12:25 PM

If you are *100%* new to Cordova, I'd suggest reading their docs. I also have a book that is great for beginners: https://www.amazon.com/Apac...

Comment 46 by Дмитрий Ковалевский posted on 1/9/2017 at 5:43 PM

What is the difference between this plugin and simple xhr request?

Comment 47 (In reply to #46) by Raymond Camden posted on 1/11/2017 at 7:41 PM

You can't use XHR to request a file outside of the web root of the app.

Comment 48 (In reply to #47) by Дмитрий Ковалевский posted on 1/17/2017 at 3:32 AM

Thank you Raymond. Now I have a new related question. I am now developing an app which contains 13 mini-games. They are mini but the weight of the whole app is about 450 Mb. My question is: can I publish the app with just three games out of 13 and the user would download the other games one by one – with that File plugin? I use Intel XDK and I can't create apk expantion file (or maybe I can but just don't know).

Comment 49 (In reply to #48) by Raymond Camden posted on 1/17/2017 at 10:24 PM

You can't change the 'structure' of your app after release, so I'm not sure this would be allowed.

Comment 50 (In reply to #41) by Web Data posted on 3/11/2017 at 5:37 PM

then how access external SD card data using cordova ?

Comment 51 (In reply to #50) by Raymond Camden posted on 3/13/2017 at 6:39 PM

I don't know - sorry.

Comment 52 by Yusuf Abdulloh posted on 7/13/2017 at 3:58 AM

Thank you, this is very helpful.

Comment 53 by Daman Daman posted on 11/27/2017 at 10:26 PM

Thanks man!

Comment 54 by stephenaidoo posted on 1/1/2018 at 10:14 AM

Thanks Very Much. Just saw this awesome article. However, please help me. I want to play the audio file from the android folder "download" or Main "Music" directory and not the application directory

Comment 55 (In reply to #54) by Raymond Camden posted on 1/2/2018 at 2:10 PM

This comment isn't on topic for this blog post at all. I'd suggest posting your question to StackOverflow.

Comment 56 by Ankit Singh posted on 10/23/2018 at 6:05 AM

Could you please tell me how can I write file in applicationDirectory. Basically all I need is to update the translation file in assets folder.

Comment 57 (In reply to #56) by Raymond Camden posted on 10/23/2018 at 1:18 PM

You should read the docs on the file plugin and make an attempt first. The docs do cover this. When you have a complete solution, even if broken, I could try to help then.