Created
May 21, 2021 23:54
-
-
Save tobiaswx/586988f80c47354adc1c80786bdaf911 to your computer and use it in GitHub Desktop.
Kotlin/JS NodeJs Process Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am grateful for everyone who contributes to this!