Skip to content

Instantly share code, notes, and snippets.

@faveoled
Created February 24, 2024 15:36
Show Gist options
  • Save faveoled/759dcfed169cafd919574acccfaee797 to your computer and use it in GitHub Desktop.
Save faveoled/759dcfed169cafd919574acccfaee797 to your computer and use it in GitHub Desktop.
Scala.js Node.js run process
def runProcess(command: String, cwd: Option[String], details: String = ""): Future[String] = {
val msg = if (details == "") then s"Running command `${command}`" else s"${details}"
println(s"${msg}...")
val options = encodingBufferEncodingExe(BufferEncoding.utf8)
cwd.foreach(cwdR => options.cwd = cwdR)
val process = node_child_process.exec(command, options)
var strBuilder = mutable.StringBuilder()
process.stdout.asInstanceOf[typings.node.streamMod.Readable].on_data(nodeStrings.data, data => {
strBuilder.append(data)
println(s"cmd stdout: $data")
})
process.stderr.asInstanceOf[typings.node.streamMod.Readable].on_data(nodeStrings.data, data => {
println(s"cmd stderr: $data")
})
val promise: Promise[String] = Promise[String]()
process.on_exit(nodeStrings.exit, (code: Double | Null, signal: Signals | Null) => {
val codeStr = Objects.toString(code)
if (codeStr == "0") {
println(s"Done: ${details}")
promise.success(strBuilder.toString)
} else {
val message = s"Command exited with code ${codeStr}"
println(message)
promise.failure(new RuntimeException(message))
}
})
promise.future
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment