0

Normally just doing FileReader.read... and catapulting on errors would be the (async.) way.

But in some cases simply checking access synchronously before initiating the actual transfer may be better (see examples below).

  • Can it be something like this (in pseudocode; based on this SO post)?
  • Can it return true without actually reading the whole file?

    function is_readable(file) { // File object
        var ok = null
    
        function check(e) {
            ok = (SOME.ERROR.CONDITION.HERE ? false : true) // perhaps: e.target.result?
        }
    
        var blob = file.slice(0, 1) // does slice() make any sense here?
        var reader = new FileReader()
    
        // not sure which events to buy:
        reader.onload = check
        reader.onerror = check
    
        reader.readAsArrayBuffer(blob)
    
        // sync here for the result:
        while (ok === null) {
            alert('...waiting...')
        }
    
        return ok
    }
    

Example cases:

  1. For batch upload (selecting files with a multi-file INPUT, and not sending them until an "Upload All" button is pressed), you want to list unreadable files in red. For this, in the list builder loop, you'd just select color for each File object f like is_readable(f) ? 'green' : 'red'.

  2. Chrome(25) doesn't seem to set an error during XMLHttpRequest.send() here for some reason, happily posting the file, but silently truncating to 0 bytes, if the file is not readable. So I'd like to check it myself beforehand, as a workaround.

(Note: I checked php.js but it doesn't seem to have this one.)

Community
  • 1
  • 1
Sz.
  • 3,342
  • 1
  • 30
  • 43
  • Your question reads more like a riddle. Can you reword please? – Ray Nicholus May 31 '13 at 00:41
  • 1
    Why are you treating an asynchronous call as synchronous? – epascarello May 31 '13 at 01:35
  • Because is_readable(), which I'd like to emulate, is a function call (which means synchronous by definition). The point of this checker function is providing a simple "instantaneous" query that is trivial to use, and can be cheaply called wherever you need it. It's purpose is to simplify the inherently more tedious and complex async procedure into something more like a trivial "propery getter". The sync. call requires nothing from the rest of your program, unlike async IO, which can't even be just a call, to begin with. – Sz. May 31 '13 at 02:02
  • Have you ever heard of the [promise pattern](http://blogs.msdn.com/b/ie/archive/2011/09/11/asynchronous-programming-in-javascript-with-promises.aspx)? – Ray Nicholus May 31 '13 at 02:28

0 Answers0