pretty-print.js 1.5 KB

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