External File Resources

It's often when developing an Application that you need to use a configuration file, some XML datas, or other kind of Text resources. In Haxe, you can use platform-specific API to access theses resources :

  • by loading them using the Browser-API in JavaScript
  • by loading them using the LoadVars object in Flash
  • by reading them on disk using the neko.File class on the Server

However, in the case of Loading, this often require you to work asynchronously, that means starting the loading process, display some message, wait until the load is completed, and then resume your application logic. While this is useful for big resources, you might need some better API for small configurations files or XML datas.

The Haxe Resources are a way to store some External File content directly into the compiled/generated code at compile time. You can use the -resource commandline parameter to link a resource file.

Text file example

For example, let's say you have a file hello_message.txt containing the following text :

Hello, this is a welcome message !

You can add the following parameter to your HXML file :

-resource hello_message.txt@welcome

To the name of the file is appended a resource identifier separated by an arrow base. In your code, you can use the Resource class to retrieve the content of the file :

class App {
    static function main() {

This code will display the content of the hello_message.txt file at the time the code was compiled. This way, you don't have to distribute the external files linked this way with your application.

Audio file example (Flash 11)

Binary files can be embedded as well, and accessed with getBytes() instead of getString(). For example, you can embed an mp3 file with this HXML parameter:

-resource assets/jump.mp3@audio-jump

In your code, you would Resource retrieve the binary contents and convert into a Sound object:

class App {
    static function main() {
        var data = haxe.Resource.getBytes("audio-jump");
        var sound = new flash.media.Sound();
        sound.loadCompressedDataFromByteArray(data.getData(), data.length);

This will play the contents of the mp3. Once loaded into the sound object, call sound.play() to play the sound again; there's no need to load it repeatedly from the resource object.

version #12360, modified 2012-02-16 04:06:10 by amitp