« get me outta code hell

Initial commit - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/general-util.js
diff options
context:
space:
mode:
authorFlorrie <towerofnix@gmail.com>2018-05-28 22:42:37 -0300
committerFlorrie <towerofnix@gmail.com>2018-05-28 22:42:37 -0300
commitb64a14b761a38da13b81370828a2d5e9ad68c330 (patch)
tree09449457e9b2dc4a6a1d1828e8c4371e0fb47eff /general-util.js
Initial commit
Diffstat (limited to 'general-util.js')
-rw-r--r--general-util.js48
1 files changed, 48 insertions, 0 deletions
diff --git a/general-util.js b/general-util.js
new file mode 100644
index 0000000..35e1103
--- /dev/null
+++ b/general-util.js
@@ -0,0 +1,48 @@
+const { spawn } = require('child_process')
+const npmCommandExists = require('command-exists')
+
+module.exports.promisifyProcess = function(proc, showLogging = true) {
+  // Takes a process (from the child_process module) and returns a promise
+  // that resolves when the process exits (or rejects, if the exit code is
+  // non-zero).
+
+  return new Promise((resolve, reject) => {
+    if (showLogging) {
+      proc.stdout.pipe(process.stdout)
+      proc.stderr.pipe(process.stderr)
+    }
+
+    proc.on('exit', code => {
+      if (code === 0) {
+        resolve()
+      } else {
+        reject(code)
+      }
+    })
+  })
+}
+
+module.exports.commandExists = async function(command) {
+  // When the command-exists module sees that a given command doesn't exist, it
+  // throws an error instead of returning false, which is not what we want.
+
+  try {
+    return await npmCommandExists(command)
+  } catch(err) {
+    return false
+  }
+}
+
+module.exports.killProcess = async function(proc) {
+  // Windows is stupid and doesn't like it when we try to kill processes.
+  // So instead we use taskkill! https://stackoverflow.com/a/28163919/4633828
+
+  if (await module.exports.commandExists('taskkill')) {
+    await module.exports.promisifyProcess(
+      spawn('taskkill', ['/pid', proc.pid, '/f', '/t']),
+      false
+    )
+  } else {
+    proc.kill()
+  }
+}