« get me outta code hell

socat.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/socat.js
blob: ca317ea231380126368b62ae5ecf34a0feeb3731 (plain)
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
// Simple interface for making a socat process and interacting with it.
// Assumes access to the `socat` command as a child process.

const EventEmitter = require('events')
const { spawn } = require('child_process')
const { killProcess } = require('./general-util')

module.exports = class Socat extends EventEmitter {
  constructor(path) {
    super()
    this.setPath(path)
  }

  setPath(path) {
    this.stop()
    this.path = path
  }

  start() {
    this.stop()
    this.subprocess = spawn('socat', ['-', this.path])
    this.subprocess.stdout.on('data', data => this.emit('data', data))
    this.subprocess.on('close', () => {
      this.subprocess = null
    })
  }

  stop() {
    if (this.subprocess) {
      killProcess(this.subprocess)
      this.subprocess = null
    }
  }

  send(message) {
    if (!this.subprocess) {
      this.start()
    }
    this.subprocess.stdin.write(message + '\r\n')
  }
}