ansi-html 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #!/usr/bin/env node
  2. var ansiHTML = require('../')
  3. var pkg = require('../package.json')
  4. var l = console.log
  5. var w = console.warn
  6. var stdoutFlushed = true
  7. var readingStdin = false
  8. function logLine (line) {
  9. if (!line) {
  10. return
  11. }
  12. line = ansiHTML(line)
  13. try {
  14. stdoutFlushed = process.stdout.write(line)
  15. } catch (e) {}
  16. }
  17. function safeExit (code) {
  18. l('')
  19. process.exit(code)
  20. }
  21. function processStdin (finish) {
  22. readingStdin = true
  23. var chunks = ''
  24. process.stdin.resume()
  25. process.stdin.setEncoding('utf-8')
  26. process.stdin.on('data', function (chunk) {
  27. var lines = chunk.split(/[\r\n]+/g).filter(function (line) {
  28. return line
  29. })
  30. var length = lines.length
  31. if (length === 1) {
  32. chunks += lines[0]
  33. return
  34. }
  35. if (length > 1) {
  36. logLine(chunks + (chunks ? '\n' : '') + lines[0] + '\n')
  37. }
  38. chunks = lines.pop()
  39. length -= 1
  40. for (var i = 1; i < length; i++) {
  41. logLine(lines[i] + '\n')
  42. }
  43. })
  44. process.stdin.on('end', function () {
  45. if (chunks) {
  46. logLine(chunks)
  47. }
  48. finish()
  49. })
  50. }
  51. function stdoutDrain (code) {
  52. process.stdout.on('drain', function () {
  53. safeExit(code)
  54. })
  55. if (stdoutFlushed) {
  56. safeExit(code)
  57. }
  58. }
  59. function startup (args) {
  60. if (args.indexOf('-h') > 0 || args.indexOf('--help') > 0) {
  61. l(pkg.name + '@' + pkg.version)
  62. l('Usage:')
  63. l(' ansi-html [options]')
  64. l(' ... | ansi-html [options]')
  65. l('Options:')
  66. l(' -h, --help print help information')
  67. return
  68. }
  69. process.stdout.on('error', function (err) {
  70. if (err.code === 'EPIPE') {
  71. stdoutDrain(0)
  72. } else {
  73. w('stdout error:', err)
  74. stdoutDrain(1)
  75. }
  76. })
  77. processStdin(function () {
  78. safeExit(0)
  79. })
  80. }
  81. if (require.main === module) {
  82. startup(process.argv)
  83. }
  84. process.on('SIGINT', function () {
  85. if (!readingStdin) {
  86. safeExit(1)
  87. }
  88. })
  89. process.on('SIGQUIT', function () { safeExit(1) })
  90. process.on('SIGTERM', function () { safeExit(1) })
  91. process.on('SIGHUP', function () { safeExit(1) })