I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

Kotlin is a next-generation programming language developed by JetBrains. It gains popularity with the Android development community as a replacement for Java.

Another exciting feature of Kotlin is the support of server- and client-side JavaScript. In this article, we’re going to discuss how to write server-side JavaScript applications using Kotlin.

Kotlin can be transpiled (source code written in one language and transformed into another language) to JavaScript. It gives users the option of targeting the JVM and JavaScript using the same language.

In the coming sections, we’re going to develop a node.js application using Kotlin.

2. node.js

Node.js is a lean, fast, cross-platform runtime environment for JavaScript. It’s useful for both server and desktop applications.

Let’s start by setting up a node.js environment and project.

2.1. Installing node.js

Node.js can be downloaded from the Node website. It comes with the npm package manager. After installing we need to set up the project.

In the empty directory, let’s run:

npm init

It will ask a few questions about package name, version description, and an entry point. Provide “kotlinNode” as name, “Kotlin Node Example”  as description and “crypto.js” as entrypoint. For the rest of the values, we’ll keep the default.

This process will generate a package.json file.

After this, we need to install a few dependency packages:

npm install
npm install kotlin --save
npm install express --save

This will install the modules required by our example application in the current project directory.

3.  Creating a node.js Application using Kotlin

In this section, we’re going to create a crypto API server using node.js in KotlinThe API will fetch some self-generated cryptocurrency rates.

3.1. Setting up the Kotlin Project

Now let’s setup the Kotlin project. We’ll be using Gradle here which is the recommended and easy to use approach. Gradle can be installed by following the instructions provided on the Gradle site.

Let’s start by creating the build.gradle file in the same directory:

buildscript {
    ext.kotlin_version = '1.2.41'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

group 'com.baeldung'
version '1.0-SNAPSHOT'
apply plugin: 'kotlin2js'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version"
}

compileKotlin2Js.kotlinOptions {
    moduleKind = "commonjs"
    outputFile = "node/crypto.js"
}

There are two important points to highlight in the build.gradle file. First, we apply the kotlin2js plugin to do the transpilation.

Then, in KotlinOptions, we set moduleKind to “commonjs” to work with node.js. With the outputFile optionwe control where the transpiled code will be generated.

3.2. Creating an API

Let’s start implementing our application by creating the source folder src/main/kotlin.

In this folder, we create the file CryptoRate.kt.

In this file, we first need to import the require function and then create the main method:

external fun require(module: String): dynamic

fun main(args: Array<String>) {
    
}

Next, we import the required modules and create a server that listens on port 3000:

val express = require("express")

val app = express()
app.listen(3000, {
    println("Listening on port 3000")
})

Finally, we add the API endpoint “/crypto”. It will generate and return the data:

app.get("/crypto", { _, res ->
    res.send(generateCrypoRates())
})

data class CryptoCurrency(var name: String, var price: Float)

fun generateCryptoRates(): Array<CryptoCurrency> {
    return arrayOf<CryptoCurrency>(
      CryptoCurrency("Bitcoin", 90000F),
      CryptoCurrency("ETH",1000F),
      CryptoCurrency("TRX",10F)
    );
}

We’ve used the node.js express module to create the API endpoint. 

4. Run the Application

Running the application will be a two-part process. We need to transpile the Kotlin code into JavaScript before we can start our application with Node.

To create the JavaScript code, we use the Gradle build task:

gradlew build

This will generate the source code in the node directory.

Next, we execute the generated code file crypto.js using Node.js:

node node/crypto.js

This will launch the server running at port 3000In the browser let’s access the API by invoking http://localhost:3000/crypto to get this JSON result:

[
  {
    "name": "Bitcoin",
    "price": 90000
  },
  {
    "name": "ETH",
    "price": 1000
  },
  {
    "name": "TRX",
    "price": 10
  }
]

Alternatively, we can use tools like Postman or SoapUI to consume the API.

5. Conclusion

In this article, we’ve learned how to write node.js applications using Kotlin.

We’ve built a small service in a few minutes without using any boilerplate code.

As always, the code samples can be found over on GitHub.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS