« get me outta code hell

heck around with socat stuff - 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:
authorFlorrie <towerofnix@gmail.com>2020-02-04 22:21:48 -0400
committerFlorrie <towerofnix@gmail.com>2020-02-04 22:22:14 -0400
commit4923c4d2b06cda8d1ba0710602f205e9cd3d9d5d (patch)
treed18890e3061a9669500c2d3ef2812802dc369da1 /socat.js
parent6a257c10b58af844c8505cb121c090071be9bf64 (diff)
heck around with socat stuff
Diffstat (limited to 'socat.js')
-rw-r--r--socat.js42
1 files changed, 31 insertions, 11 deletions
diff --git a/socat.js b/socat.js
index ca317ea..8c6b9ed 100644
--- a/socat.js
+++ b/socat.js
@@ -1,9 +1,15 @@
 // Simple interface for making a socat process and interacting with it.
-// Assumes access to the `socat` command as a child process.
+// 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 } = require('./general-util')
+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) {
@@ -16,13 +22,15 @@ module.exports = class Socat extends EventEmitter {
     this.path = path
   }
 
-  start() {
+  async 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
-    })
+    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() {
@@ -32,10 +40,22 @@ module.exports = class Socat extends EventEmitter {
     }
   }
 
-  send(message) {
+  async send(message) {
     if (!this.subprocess) {
-      this.start()
+      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.)
+      }
     }
-    this.subprocess.stdin.write(message + '\r\n')
   }
 }