ansi-html
1.99 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env node
var ansiHTML = require('../')
var pkg = require('../package.json')
var l = console.log
var w = console.warn
var stdoutFlushed = true
var readingStdin = false
function logLine (line) {
if (!line) {
return
}
line = ansiHTML(line)
try {
stdoutFlushed = process.stdout.write(line)
} catch (e) {}
}
function safeExit (code) {
l('')
process.exit(code)
}
function processStdin (finish) {
readingStdin = true
var chunks = ''
process.stdin.resume()
process.stdin.setEncoding('utf-8')
process.stdin.on('data', function (chunk) {
var lines = chunk.split(/[\r\n]+/g).filter(function (line) {
return line
})
var length = lines.length
if (length === 1) {
chunks += lines[0]
return
}
if (length > 1) {
logLine(chunks + (chunks ? '\n' : '') + lines[0] + '\n')
}
chunks = lines.pop()
length -= 1
for (var i = 1; i < length; i++) {
logLine(lines[i] + '\n')
}
})
process.stdin.on('end', function () {
if (chunks) {
logLine(chunks)
}
finish()
})
}
function stdoutDrain (code) {
process.stdout.on('drain', function () {
safeExit(code)
})
if (stdoutFlushed) {
safeExit(code)
}
}
function startup (args) {
if (args.indexOf('-h') > 0 || args.indexOf('--help') > 0) {
l(pkg.name + '@' + pkg.version)
l('Usage:')
l(' ansi-html [options]')
l(' ... | ansi-html [options]')
l('Options:')
l(' -h, --help print help information')
return
}
process.stdout.on('error', function (err) {
if (err.code === 'EPIPE') {
stdoutDrain(0)
} else {
w('stdout error:', err)
stdoutDrain(1)
}
})
processStdin(function () {
safeExit(0)
})
}
if (require.main === module) {
startup(process.argv)
}
process.on('SIGINT', function () {
if (!readingStdin) {
safeExit(1)
}
})
process.on('SIGQUIT', function () { safeExit(1) })
process.on('SIGTERM', function () { safeExit(1) })
process.on('SIGHUP', function () { safeExit(1) })