UNPKG

1.49 kBJavaScriptView Raw
1var sax = require("../lib/sax")
2 , printer = sax.createStream(false, {lowercasetags:true, trim:true})
3 , fs = require("fs")
4
5function entity (str) {
6 return str.replace('"', '"')
7}
8
9printer.tabstop = 2
10printer.level = 0
11printer.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}
19printer.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
29printer.on("text", ontext)
30printer.on("doctype", ontext)
31function ontext (text) {
32 this.indent()
33 print(text)
34}
35
36printer.on("closetag", function (tag) {
37 this.level --
38 this.indent()
39 print("</"+tag+">")
40})
41
42printer.on("cdata", function (data) {
43 this.indent()
44 print("<![CDATA["+data+"]]>")
45})
46
47printer.on("comment", function (comment) {
48 this.indent()
49 print("<!--"+comment+"-->")
50})
51
52printer.on("error", function (error) {
53 console.error(error)
54 throw error
55})
56
57if (!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}
61var xmlfile = require("path").join(process.cwd(), process.argv[2])
62var fstr = fs.createReadStream(xmlfile, { encoding: "utf8" })
63
64function print (c) {
65 if (!process.stdout.write(c)) {
66 fstr.pause()
67 }
68}
69
70process.stdout.on("drain", function () {
71 fstr.resume()
72})
73
74fstr.pipe(printer)