1 | var sax = require("../lib/sax")
|
2 | , printer = sax.createStream(false, {lowercasetags:true, trim:true})
|
3 | , fs = require("fs")
|
4 |
|
5 | function entity (str) {
|
6 | return str.replace('"', '"')
|
7 | }
|
8 |
|
9 | printer.tabstop = 2
|
10 | printer.level = 0
|
11 | printer.indent = function () {
|
12 | print("\n")
|
13 | for (var i = this.level; i > 0; i --) {
|
14 | for (var j = this.tabstop; j > 0; j --) {
|
15 | print(" ")
|
16 | }
|
17 | }
|
18 | }
|
19 | printer.on("opentag", function (tag) {
|
20 | this.indent()
|
21 | this.level ++
|
22 | print("<"+tag.name)
|
23 | for (var i in tag.attributes) {
|
24 | print(" "+i+"=\""+entity(tag.attributes[i])+"\"")
|
25 | }
|
26 | print(">")
|
27 | })
|
28 |
|
29 | printer.on("text", ontext)
|
30 | printer.on("doctype", ontext)
|
31 | function ontext (text) {
|
32 | this.indent()
|
33 | print(text)
|
34 | }
|
35 |
|
36 | printer.on("closetag", function (tag) {
|
37 | this.level --
|
38 | this.indent()
|
39 | print("</"+tag+">")
|
40 | })
|
41 |
|
42 | printer.on("cdata", function (data) {
|
43 | this.indent()
|
44 | print("<![CDATA["+data+"]]>")
|
45 | })
|
46 |
|
47 | printer.on("comment", function (comment) {
|
48 | this.indent()
|
49 | print("<!--"+comment+"-->")
|
50 | })
|
51 |
|
52 | printer.on("error", function (error) {
|
53 | console.error(error)
|
54 | throw error
|
55 | })
|
56 |
|
57 | if (!process.argv[2]) {
|
58 | throw new Error("Please provide an xml file to prettify\n"+
|
59 | "TODO: read from stdin or take a file")
|
60 | }
|
61 | var xmlfile = require("path").join(process.cwd(), process.argv[2])
|
62 | var fstr = fs.createReadStream(xmlfile, { encoding: "utf8" })
|
63 |
|
64 | function print (c) {
|
65 | if (!process.stdout.write(c)) {
|
66 | fstr.pause()
|
67 | }
|
68 | }
|
69 |
|
70 | process.stdout.on("drain", function () {
|
71 | fstr.resume()
|
72 | })
|
73 |
|
74 | fstr.pipe(printer)
|