-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathreader.js
More file actions
101 lines (82 loc) · 1.58 KB
/
reader.js
File metadata and controls
101 lines (82 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* Module dependencies.
*/
var Emitter = require('emitter');
/**
* Expose `reader()`.
*/
module.exports = reader;
/**
* Initialize a new `Reader` from optional `reader`
* or a new `FileReader` is created.
*
* @param {FileReader} reader
* @return {Reader}
* @api public
*/
function reader(reader) {
return reader
? new Reader(reader)
: new Reader(new FileReader);
}
/**
* Initialize a new `Reader`, a wrapper
* around a `FileReader`.
*
* Emits:
*
* - `error` an error occurred
* - `progress` in progress (`e.percent` etc)
* - `end` read is complete
*
* @param {FileReader} reader
* @api private
*/
function Reader(reader) {
Emitter.call(this);
this.reader = reader;
reader.onerror = this.emit.bind(this, 'error');
reader.onabort = this.emit.bind(this, 'error', new Error('abort'));
reader.onprogress = this.onprogress.bind(this);
reader.onload = this.onload.bind(this);
}
/**
* Inherits from `Emitter.prototype`.
*/
Emitter(Reader.prototype);
/**
* Onload handler.
*
* @api private
*/
Reader.prototype.onload = function(e){
this.emit('end', this.reader.result);
};
/**
* Progress handler.
*
* @api private
*/
Reader.prototype.onprogress = function(e){
e.percent = e.loaded / e.total * 100 | 0;
this.emit('progress', e);
};
/**
* Abort.
*
* @api public
*/
Reader.prototype.abort = function(){
this.reader.abort();
};
/**
* Read `file` as `type`.
*
* @param {File} file
* @param {String} type
* @api private
*/
Reader.prototype.read = function(file, type){
var method = 'readAs' + type;
this.reader[method](file);
};