Search code examples
node.jskotlinkotlin-js

Getting command line arguments for Kotlin/JS Node process


I have a very basic Kotlin/JS application targeting Node.js through the Gradle plugin. I want to read the command line arguments passed to the process when I execute it (using node build/js/packages/node-so-repro/kotlin/node-so-repro.js myArgument).

I am trying to use the following code to access the number of args when running the program:

fun main(args: Array<String>) {
    console.log(args.size)
}

However, this code always returns 0, even when I add command line arguments.

I have not changed the build file much from what was generated by the wizard:

kotlin {
    js {
        nodejs {
            binaries.executable()
        }
    }
}

If args does not work, how can I access the command line arguments in a Kotlin/JS Node application?


Solution

  • Node.js process arguments are currently not being translated to Kotlin's main function arguments – this is something the team is aware of, and you can follow progress on it in the "KJS / NodeJS: process.argv[2..] should be translated to main function args" issue on Kotlin's YouTrack.

    As a workaround, you can access the process's argv directly, using slice to remove node and your program path:

    external val process: dynamic
    
    fun main(args: Array<String>) {
        val argv = process.argv.slice(2) as Array<String>;
        println(argv.joinToString("; ")) // prints all arguments semi-colon separated
    }