Twitter: raymondcamden


Address: Lafayette, LA, USA

Cordova Sample: Reading a text file

07-15-2014 7,001 views Mobile, JavaScript, HTML5 14 Comments

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

14 Comments

  • Martin Cisneros Capistrán #
    Commented on 07-15-2014 at 5:00 PM
    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/cordova-plugin-camera/bl...

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

    Just why? :/
  • Martin Cisneros Capistrán #
    Commented on 07-15-2014 at 5:01 PM
    Sorry the second link is

    http://docs.phonegap.com/en/3.3.0/cordova_camera_c...
  • Martin Cisneros Capistrán #
    Commented on 07-15-2014 at 5:03 PM
    I can't post the original link hehe:

    http://docs.phonegap.com/en/3.3.0/cordova(underscore)camera(underscore)camera.md.html#Camera
  • anchal arora #
    Commented on 07-16-2014 at 4:48 AM
    I am getting an error
    uncaught TypeError :
    cannot read property 'application directory' of undefined
    can u please help me..
  • Commented on 07-16-2014 at 10:07 AM
    @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.
  • Martin Cisneros Capistrán #
    Commented on 07-16-2014 at 12:37 PM
    Oh i see, thank you!
  • Commented on 08-06-2014 at 2: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.
  • Commented on 08-06-2014 at 7:00 AM
    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.
  • Commented on 08-06-2014 at 2:13 PM
    Thanks for that insight Raymond.
  • Commented on 08-18-2014 at 5:29 PM
    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?
  • Commented on 08-18-2014 at 5:45 PM
    I believe it is this issue: https://issues.apache.org/jira/browse/CB-7273

    It came up from an issue on my repo: https://github.com/cfjedimaster/Cordova-Examples/i...
  • Commented on 10-16-2014 at 3:09 PM
    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?
  • Commented on 10-17-2014 at 12:06 PM
    Until I get time to make a little demo like the one here, the best I can suggest is the docs.
  • Commented on 10-17-2014 at 12: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!

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty