Hey guys, does anyone know how to check in Kotlin ...
# javascript
j
Hey guys, does anyone know how to check in Kotlin whether I'm running in NodeJS or in a browser? I tried to test the presence of
window
but it's always non-null in Kotlin, it just fails at runtime on NodeJS.
d
Could you
unsafeCast
it to something nullable, or wrap it in a try/catch?
j
Being a JS
ReferenceError
I didn't even think of catching it to be honest... but
catch(Throwable)
does work. Good point. I was hoping for something more built-in though, as part of the Kotlin JS stdlib
h
These checks are used by Ktor:
Copy code
public actual val IS_BROWSER: Boolean = js(
        "typeof window !== 'undefined' && typeof window.document !== 'undefined'"
    ) as Boolean

    public actual val IS_NODE: Boolean = js(
        "typeof process !== 'undefined' && process.versions != null && process.versions.node != null"
    ) as Boolean
🙏 1
j
Thanks, this looks better than catching a
ReferenceError
to me 🙂 but still it would be great if that was in the stdlib
h
I would rather see https://youtrack.jetbrains.com/issue/KT-47038 than this hack :D
1
j
+1000 to that of course