-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.js
57 lines (48 loc) · 1.41 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
var fs = require('fs')
var url = require('url')
var path = require('path')
var request = require('phin')
var parseASCII = require('parse-bmfont-ascii')
var parseXML = require('parse-bmfont-xml')
var readBinary = require('parse-bmfont-binary')
var mime = require('mime')
var noop = function() {}
var isBinary = require('./lib/is-binary')
function parseFont(file, data, cb) {
var result, binary
if (isBinary(data)) {
if (typeof data === 'string') data = Buffer.from(data, 'binary')
binary = true
} else data = data.toString().trim()
try {
if (binary) result = readBinary(data)
else if (/json/.test(mime.lookup(file)) || data.charAt(0) === '{')
result = JSON.parse(data)
else if (/xml/.test(mime.lookup(file)) || data.charAt(0) === '<')
result = parseXML(data)
else result = parseASCII(data)
} catch (e) {
cb(e)
cb = noop
}
cb(null, result)
}
module.exports = function loadFont(opt, cb) {
cb = typeof cb === 'function' ? cb : noop
if (typeof opt === 'string') opt = { uri: opt, url: opt }
else if (!opt) opt = {}
var file = opt.uri || opt.url
function handleData(err, data) {
if (err) return cb(err)
parseFont(file, data.body || data, cb)
}
if (url.parse(file).host) {
request(opt).then(function (res) {
handleData(null, res)
}).catch(function (err) {
handleData(err)
})
} else {
fs.readFile(file, opt, handleData)
}
}