-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (69 loc) · 1.99 KB
/
index.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
'use strict';
const path = require('path');
function getEncoding(options) {
const type = typeof options;
if (!options) {
return options;
} else if (type === 'string' || options instanceof String) {
return options;
} else if (type == 'object') {
return options.encoding;
} else {
throw new TypeError(
`"options" must be a string or an object, got ${type} instead.`)
}
}
function readFile(filePath, options, callback) {
if (typeof filePath !== 'string' && !(filePath instanceof String)) {
throw new TypeError("path must be a string");
}
if (callback === undefined) {
callback = options;
options = undefined;
}
const encoding = getEncoding(options);
const req = new XMLHttpRequest();
req.open('GET', 'file://' + path.resolve(filePath));
req.responseType = 'arraybuffer';
req.addEventListener('readystatechange', () => {
if (req.readyState === 4) {
if (req.status === 200 || req.status === 0) {
const buff = Buffer.from(req.response);
if (encoding) {
try {
callback(null, buff.toString(encoding));
} catch (ex) {
callback(ex, null);
}
} else {
callback(null, buff);
}
} else {
// FIXME Handle errors
callback(req.statusText, null);
}
}
});
req.send();
}
function readFileSync(filePath, options) {
if (typeof filePath !== 'string' && !(filePath instanceof String)) {
throw new TypeError("path must be a string");
}
const encoding = getEncoding(options);
if (encoding !== 'utf8') {
throw new Error(
`only utf8 encoding is allowed for synchronous reads got ${encoding}`);
}
const req = new XMLHttpRequest();
req.open('GET', 'file://' + path.resolve(filePath), false);
req.send();
if (req.status === 200 || req.status === 0) {
return req.responseText;
} else {
// FIXME Handle errors
throw req.statusText;
}
}
module.exports.readFile = readFile;
module.exports.readFileSync = readFileSync;