« 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: 8c6b9edd99c9ada9d1531a3d19c8256f607a1006 (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 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.

const EventEmitter = require('events')
const { spawn } = require('child_process')
const { killProcess, commandExists } = require('./general-util')
const { promisify } = require('util')
const fs = require('fs')
const path = require('path')

const writeFile = promisify(fs.writeFile)

module.exports = 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
      })
    }
  }

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

  async send(message) {
    if (!this.subprocess) {
      await this.start()
    }
    if (this.subprocess) {
      this.subprocess.stdin.write(message + '\r\n')
    } else {
      try {
        await writeFile(path.resolve(__dirname, 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.)
      }
    }
  }
}