forked from pinojs/pino-socket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
psock.js
98 lines (89 loc) · 2.32 KB
/
psock.js
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
'use strict'
const path = require('path')
const tcpConnectionFactory = require(path.join(__dirname, 'lib', 'TcpConnection'))
const udpConnectionFactory = require(path.join(__dirname, 'lib', 'UdpConnection'))
const split2 = require('split2')
const pump = require('pump')
const through2 = require('through2')
const nopt = require('nopt')
const fs = require('fs')
let options = {
address: '127.0.0.1',
mode: 'udp',
port: '514',
echo: true,
reconnect: false,
reconnectTries: Infinity,
settings: null
}
const longOpts = {
address: String,
mode: ['tcp', 'udp'],
port: Number,
reconnect: Boolean,
reconnectTries: Number,
echo: Boolean,
help: Boolean,
version: Boolean,
settings: String
}
const shortOpts = {
a: '--address',
m: '--mode',
p: '--port',
r: '--reconnect',
t: '--reconnectTries',
e: '--echo',
ne: '--no-echo',
h: '--help',
v: '--version',
s: '--settings'
}
const argv = nopt(longOpts, shortOpts, process.argv)
options = Object.assign(options, argv)
if (options.help) {
console.log(fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf8'))
process.exit(0)
}
if (options.version) {
console.log('pino-socket', require('./package.json').version)
process.exit(0)
}
if (options.settings) {
try {
const loadedSettings = require(path.resolve(options.settings))
const settings = Object.assign(loadedSettings, argv)
options = Object.assign(options, settings)
} catch (e) {
console.error('`settings` parameter specified but could not load file: %s', e.message)
process.exit(1)
}
}
let connection
if (options.mode === 'tcp') {
connection = tcpConnectionFactory(options)
} else {
connection = udpConnectionFactory(options)
}
function shutdown () {
try {
connection.close()
} catch (e) {
// I assume that due to the closing of the pipe, the dgram/tcp socket has
// some issues shutting down gracefully. Don't really care, though. So
// this try/catch is here to suppress the resulting error.
process.exit()
}
}
process.on('SIGINT', function sigint () {
shutdown()
})
process.on('SIGTERM', function sigterm () {
shutdown()
})
const myTransport = through2.obj(function transport (chunk, enc, cb) {
setImmediate(() => console.log(chunk))
cb()
})
process.stdin.on('close', () => { shutdown() })
if (options.echo) pump(process.stdin, split2(), myTransport)