browser.js
2.64 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
var xhr = require('xhr')
var noop = function(){}
var parseASCII = require('parse-bmfont-ascii')
var parseXML = require('parse-bmfont-xml')
var readBinary = require('parse-bmfont-binary')
var isBinaryFormat = require('./lib/is-binary')
var xtend = require('xtend')
var xml2 = (function hasXML2() {
return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
})()
module.exports = function(opt, cb) {
cb = typeof cb === 'function' ? cb : noop
if (typeof opt === 'string')
opt = { uri: opt }
else if (!opt)
opt = {}
var expectBinary = opt.binary
if (expectBinary)
opt = getBinaryOpts(opt)
xhr(opt, function(err, res, body) {
if (err)
return cb(err)
if (!/^2/.test(res.statusCode))
return cb(new Error('http status code: '+res.statusCode))
if (!body)
return cb(new Error('no body result'))
var binary = false
//if the response type is an array buffer,
//we need to convert it into a regular Buffer object
if (isArrayBuffer(body)) {
var array = new Uint8Array(body)
body = Buffer.from(array, 'binary')
}
//now check the string/Buffer response
//and see if it has a binary BMF header
if (isBinaryFormat(body)) {
binary = true
//if we have a string, turn it into a Buffer
if (typeof body === 'string')
body = Buffer.from(body, 'binary')
}
//we are not parsing a binary format, just ASCII/XML/etc
if (!binary) {
//might still be a buffer if responseType is 'arraybuffer'
if (Buffer.isBuffer(body))
body = body.toString(opt.encoding)
body = body.trim()
}
var result
try {
var type = res.headers['content-type']
if (binary)
result = readBinary(body)
else if (/json/.test(type) || body.charAt(0) === '{')
result = JSON.parse(body)
else if (/xml/.test(type) || body.charAt(0) === '<')
result = parseXML(body)
else
result = parseASCII(body)
} catch (e) {
cb(new Error('error parsing font '+e.message))
cb = noop
}
cb(null, result)
})
}
function isArrayBuffer(arr) {
var str = Object.prototype.toString
return str.call(arr) === '[object ArrayBuffer]'
}
function getBinaryOpts(opt) {
//IE10+ and other modern browsers support array buffers
if (xml2)
return xtend(opt, { responseType: 'arraybuffer' })
if (typeof self.XMLHttpRequest === 'undefined')
throw new Error('your browser does not support XHR loading')
//IE9 and XML1 browsers could still use an override
var req = new self.XMLHttpRequest()
req.overrideMimeType('text/plain; charset=x-user-defined')
return xtend({
xhr: req
}, opt)
}