title: Writing binary data from javascript (Firefox plugin)
body: <p>Hi: I'm writing a firefox extension (my first) that among other things, gets an image url read into a byte Array, and then writes out that binary information to a file. I have used <a href="https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Writing_a_Binary_File" rel="nofollow">this example</a>, which looks as if it works, but the file is not right, as if some sort of character conversion has been performed on it. </p>
  
  <p>My version is as follows:</p>
  
  <pre class="lang-js prettyprint-override"><code>testWriteBinaryFile : function (dir, filename, data) {
      var aFile = Components.classes["@mozilla.org/file/local;1"].
          createInstance(Components.interfaces.nsILocalFile);
  
      aFile.initWithPath( "/home/mike/mypicture.gif" );
      aFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
      Firebug.Console.log("Binary writing: file set up");
  
      var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
                   createInstance(Components.interfaces.nsIFileOutputStream);
      stream.init(aFile, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate
      Firebug.Console.log("Binary writing: stream set up");
  
      Firebug.Console.log("Data length: " + data.length);
      Firebug.Console.log("Data byte 0: " + data[0].toString(16));
      Firebug.Console.log("Data byte 1: " + data[1].toString(16));
      Firebug.Console.log("Data byte 2: " + data[2].toString(16));
      Firebug.Console.log("Data byte 3: " + data[3].toString(16));
      Firebug.Console.log("Data byte 4: " + data[4].toString(16));
  
      stream.write(data, data.length);
      Firebug.Console.log("Binary writing: stream written")
      if (stream instanceof Components.interfaces.nsISafeOutputStream) {
          stream.finish();
      } else {
          stream.close();
      }
      Firebug.Console.log("Binary writing: done.");
  }
  </code></pre>
  
  <p>I know the data buffer itself is OK by printing out the first few bytes, but the file is completely different once on disk. Any ideas or indeed any other ways to write out a binary file? </p>
  
  <p>I know this is a synchronous write, but the files are small, (20Kb)... but that's the only example. If I can fix this I have the extension finished! Any and all help appreciated.</p>