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
|
// Simple interface for making a socat process and interacting with it.
// Assumes access to the `socat` command as a child process; if it's not
// present, it will fall back to just writing to the specified file.
import {spawn} from 'node:child_process'
import {writeFile} from 'node:fs/promises'
import EventEmitter from 'node:events'
import path from 'node:path'
import {killProcess, commandExists} from './general-util.js'
export default class Socat extends EventEmitter {
constructor(path) {
super()
this.setPath(path)
}
setPath(path) {
this.stop()
this.path = path
}
async start() {
this.stop()
if (await commandExists('socat')) {
this.subprocess = spawn('socat', ['-', this.path])
this.subprocess.stdout.on('data', data => this.emit('data', data))
this.subprocess.on('close', () => {
this.subprocess = null
})
this.subprocess.stdin.on('error', () => {
this.stop()
})
}
}
async stop() {
const proc = this.subprocess
if (proc) {
this.subprocess = null
await killProcess(proc)
}
}
async dispose() {
// Don't accept any more messages.
this.disposed = true
await this.stop()
}
async send(message) {
if (this.disposed) {
return
}
if (!this.subprocess) {
await this.start()
}
if (this.subprocess) {
try {
this.subprocess.stdin.write(message + '\r\n')
} catch (error) {
// There's no guarantee we'll actually suceed to write - the process
// or pipe we're writing to could have closed unexpectedly. If that
// happens, unestablish the socat process; it'll try to reconnect if
// we send another message.
this.stop()
}
} else {
try {
await writeFile(path.resolve(process.cwd(), this.path), message + '\r\n')
} catch (error) {
// :shrug: We tried!
// -- It's possible to get here if the specified path isn't an actual
// device, which is the case on Linux. Writing to that file (hopefully)
// works on Windows though, which is the case we're trying to support
// here. (On Linux you should have socat installed.)
}
}
}
}
|