Skip to content

Instantly share code, notes, and snippets.

@tobiaswx
Created May 21, 2021 23:54
Show Gist options
  • Save tobiaswx/586988f80c47354adc1c80786bdaf911 to your computer and use it in GitHub Desktop.
Save tobiaswx/586988f80c47354adc1c80786bdaf911 to your computer and use it in GitHub Desktop.
Kotlin/JS NodeJs Process Class
plugins {
kotlin("js") version "1.5.0"
kotlin("plugin.serialization") version "1.5.0"
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1")
// ...
}
// Remaining entries omitted in favor of readability
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
// The variables and functions I use most according to: https://nodejs.org/api/process.html#process_process_env
@JsName("process")
external object Process {
val argv: Array<String>
val env: dynamic
val arch: String
val execArgv: Array<String>
val execPath: String
val exitCode: Int
var title: String
val versions: dynamic
fun cwd(): String
fun exit(code: Int = definedExternally)
fun getegid(): Int
fun geteuid(): Int
fun getgid(): Int
fun getgroups(): Array<Int>
fun getuid(): Array<Int>
fun uptime(): Number
fun on(event: String, block: (dynamic) -> Unit)
}
fun Process.args(): Array<String> = argv.slice(2 until argv.size).toTypedArray()
fun Process.env(): JsonObject = asJsonObject(env)
fun Process.versions(): JsonObject = asJsonObject(versions)
// Maybe there is a better way, but it works
private fun asJsonObject(o: Any?): JsonObject {
val jsonString = JSON.stringify(o)
val jsonElement = Json.parseToJsonElement(jsonString)
return jsonElement as JsonObject
}
object ProcessEvents {
fun onBeforeExit(block: (code: Int) -> Unit) {
Process.on("beforeExit", block)
}
fun onExit(block: (code: Int) -> Unit) {
Process.on("exit", block)
}
}
@tobiaswx
Copy link
Author

I am grateful for everyone who contributes to this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment