« get me outta code hell

mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/socat.js
diff options
context:
space:
mode:
Diffstat (limited to 'socat.js')
-rw-r--r--socat.js41
1 files changed, 41 insertions, 0 deletions
diff --git a/socat.js b/socat.js
new file mode 100644
index 0000000..ca317ea
--- /dev/null
+++ b/socat.js
@@ -0,0 +1,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')
+  }
+}