-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.coffee
63 lines (60 loc) · 2.07 KB
/
index.coffee
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
sax = require 'sax'
last = (array) -> array[array.length-1]
exports.createParser = (cbError, cbFinished, wantedNodes, strict) ->
interestingStack = []
element = null
parser = sax.parser strict
parser.onerror = cbError
parser.onend = cbFinished
parser.onopentag = ({name, attributes}) ->
if wantedNodes[name]? or element?
parent = element
element = {parent, name, attributes, children: {all: [], tags: [], text: []}}
if parent?
parent.children.all.push element
if not parent.children.tags[name]?
parent.children.tags[name] = new Array
parent.children.tags[name].push element
if wantedNodes[name]?
interestingStack.push name
parser.onclosetag = (name) ->
if name is last interestingStack
interestingStack.pop()
wantedNodes[name] element
element = element?.parent
parser.ontext = (text) ->
element?.children.all.push text
element?.children.text.push text
parser.oncdata = (text) ->
element?.children.all.push text
element?.children.text.push text
parser
exports.createStream = (cbError, cbFinished, wantedNodes, strict) ->
interestingStack = []
element = null
stream = sax.createStream strict
stream.on "error" , cbError
stream.on "end" , cbFinished
stream.on "opentag", ({name, attributes}) ->
if wantedNodes[name]? or element?
parent = element
element = {parent, name, attributes, children: {all: [], tags: [], text: []}}
if parent?
parent.children.all.push element
if not parent.children.tags[name]?
parent.children.tags[name] = new Array
parent.children.tags[name].push element
if wantedNodes[name]?
interestingStack.push name
stream.on "closetag", (name) ->
if name is last interestingStack
interestingStack.pop()
wantedNodes[name] element
element = element?.parent
stream.on "text", (text) ->
element?.children.all.push text
element?.children.text.push text
stream.on "cdata", (text) ->
element?.children.all.push text
element?.children.text.push text
stream