forked from node-file-api/FileReader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileReader.js
300 lines (246 loc) · 7.1 KB
/
FileReader.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//
// FileReader
//
// http://www.w3.org/TR/FileAPI/#dfn-filereader
// https://developer.mozilla.org/en/DOM/FileReader
(function () {
"use strict";
var fs = require("fs")
, EventEmitter = require("events").EventEmitter
;
function doop(fn, args, context) {
if ('function' === typeof fn) {
fn.apply(context, args);
}
}
function toDataUrl(data, type) {
// var data = self.result;
var dataUrl = 'data:';
if (type) {
dataUrl += type + ';';
}
if (/text/i.test(type)) {
dataUrl += 'charset=utf-8,';
dataUrl += data.toString('utf8');
} else {
dataUrl += 'base64,';
dataUrl += data.toString('base64');
}
return dataUrl;
}
function mapDataToFormat(file, data, format, encoding) {
// var data = self.result;
switch(format) {
case 'buffer':
return data;
break;
case 'binary':
return data.toString('binary');
break;
case 'dataUrl':
return toDataUrl(data, file.type);
break;
case 'text':
return data.toString(encoding || 'utf8');
break;
}
}
function FileReader() {
var self = this,
emitter = new EventEmitter,
file;
self.addEventListener = function (on, callback) {
emitter.on(on, callback);
};
self.removeEventListener = function (callback) {
emitter.removeListener(callback);
}
self.dispatchEvent = function (on) {
emitter.emit(on);
}
self.EMPTY = 0;
self.LOADING = 1;
self.DONE = 2;
self.error = undefined; // Read only
self.readyState = self.EMPTY; // Read only
self.result = undefined; // Road only
// non-standard
self.on = function () {
emitter.on.apply(emitter, arguments);
}
self.nodeChunkedEncoding = false;
self.setNodeChunkedEncoding = function (val) {
self.nodeChunkedEncoding = val;
};
// end non-standard
// Whatever the file object is, turn it into a Node.JS File.Stream
function createFileStream() {
var stream = new EventEmitter(),
chunked = self.nodeChunkedEncoding;
// attempt to make the length computable
if (!file.size && chunked && file.path) {
fs.stat(file.path, function (err, stat) {
file.size = stat.size;
file.lastModifiedDate = stat.mtime;
});
}
// The stream exists, do nothing more
if (file.stream) {
return;
}
// Create a read stream from a buffer
if (file.buffer) {
process.nextTick(function () {
stream.emit('data', file.buffer);
stream.emit('end');
});
file.stream = stream;
return;
}
// Create a read stream from a file
if (file.path) {
// TODO url
if (!chunked) {
fs.readFile(file.path, function (err, data) {
if (err) {
stream.emit('error', err);
}
if (data) {
stream.emit('data', data);
stream.emit('end');
}
});
file.stream = stream;
return;
}
// TODO don't duplicate this code here,
// expose a method in File instead
file.stream = fs.createReadStream(file.path);
}
}
// before any other listeners are added
emitter.on('abort', function () {
self.readyState = self.DONE;
});
// Map `error`, `progress`, `load`, and `loadend`
function mapStreamToEmitter(format, encoding) {
var stream = file.stream,
buffers = [],
chunked = self.nodeChunkedEncoding;
buffers.dataLength = 0;
stream.on('error', function (err) {
if (self.DONE === self.readyState) {
return;
}
self.readyState = self.DONE;
self.error = err;
emitter.emit('error', err);
});
stream.on('data', function (data) {
if (self.DONE === self.readyState) {
return;
}
buffers.dataLength += data.length;
buffers.push(data);
emitter.emit('progress', {
// fs.stat will probably complete before this
// but possibly it will not, hence the check
lengthComputable: (!isNaN(file.size)) ? true : false,
loaded: buffers.dataLength,
total: file.size
});
emitter.emit('data', data);
});
stream.on('end', function () {
if (self.DONE === self.readyState) {
return;
}
var data;
if (buffers.length > 1 ) {
data = Buffer.concat(buffers);
} else {
data = buffers[0];
}
self.readyState = self.DONE;
self.result = mapDataToFormat(file, data, format, encoding);
emitter.emit('load', {
target: {
// non-standard
nodeBufferResult: data,
result: self.result
}
});
emitter.emit('loadend');
});
}
// Abort is overwritten by readAsXyz
self.abort = function () {
if (self.readState == self.DONE) {
return;
}
self.readyState = self.DONE;
emitter.emit('abort');
};
//
function mapUserEvents() {
emitter.on('start', function () {
doop(self.onloadstart, arguments);
});
emitter.on('progress', function () {
doop(self.onprogress, arguments);
});
emitter.on('error', function (err) {
// TODO translate to FileError
if (self.onerror) {
self.onerror(err);
} else {
if (!emitter.listeners.error || !emitter.listeners.error.length) {
throw err;
}
}
});
emitter.on('load', function () {
doop(self.onload, arguments);
});
emitter.on('loadend', function () {
doop(self.onloadend, arguments);
});
emitter.on('abort', function () {
doop(self.onabort, arguments);
});
}
function readFile(_file, format, encoding) {
file = _file;
if (!file || !file.name || !(file.path || file.stream || file.buffer)) {
throw new Error("cannot read as File: " + JSON.stringify(file));
}
if (0 !== self.readyState) {
console.log("already loading, request to change format ignored");
return;
}
// 'process.nextTick' does not ensure order, (i.e. an fs.stat queued later may return faster)
// but `onloadstart` must come before the first `data` event and must be asynchronous.
// Hence we waste a single tick waiting
process.nextTick(function () {
self.readyState = self.LOADING;
emitter.emit('loadstart');
createFileStream();
mapStreamToEmitter(format, encoding);
mapUserEvents();
});
}
self.readAsArrayBuffer = function (file) {
readFile(file, 'buffer');
};
self.readAsBinaryString = function (file) {
readFile(file, 'binary');
};
self.readAsDataURL = function (file) {
readFile(file, 'dataUrl');
};
self.readAsText = function (file, encoding) {
readFile(file, 'text', encoding);
};
}
module.exports = FileReader;
}());