Kotlin is a language from JetBrains that has a much simpler syntax than Java. It can be compiled to Java Classes and JavaScript. Node.js is JavaScript that can run on the server side. Build a server application written by Kotlin
create
Open Idea to create a Kotlin(JavaScript) project and write a test file to check if it compiles properly
Test.kt
fun main(args: Array<String>) {
println("hello kt")
}
Copy the code
{projectName}.js is the compiled file. If you open it, you can see that it has been compiled into JavaScript. Println (‘hello kt’) is also in it. If that’s ok, we can start the next step, creating app.kt
App.kt
Listening on port 8888 returns Hello World on any request
import kotlin.js.json
external fun require(module: String): dynamic
fun main(args: Array<String>) {
println("hello kt")
val http = require("http")
http.createServer { _, response ->
response.writeHead(200, json("Content-Type" to "text/plain"))
response.end("Hello World")
}.listen(8888)
}
Copy the code
NPM
Open terminal running
$ npm init
Copy the code
package.json
{" name ":" kt - node ", "version" : "1.0.0", "description" : "kt - node", "scripts" : {" start ": "Node./out/production/kt-node/kt-node.js", "author": "laziji", "author": "laziji", "dependencies": {"express": "^ 4.15.4 kotlin", ""," ^ 1.1.4 ", "mongoose" : "^ 4.11.7"}}Copy the code
$ npm install
$ npm start
Copy the code
Open localhost:8888 to view the result
If there is an error
If an error occurs at runtime, open Project Settings -> Kotlin Complier, change Module kind to UMD, and try to compile and run again