Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load resource file (json) in kotlin js

Given this code, where should I place the file.json to be able to be found in the runtime?

// path: src/main/kotlin/Server.kt
fun main() {
  val serviceAccount = require("file.json")
}

I tried place it under src/main/resources/ without luck. I also use Gradle to compile kotlin to js with kotlin2js plugin.

like image 591
Diolor Avatar asked Mar 11 '19 22:03

Diolor


1 Answers

Assuming the Kotlin compiler puts the created JS file (say server.js) into the default location at build/classes/kotlin/main and the resource file (file.json) into build/resources/main.

And you are running server.js by executing node build/classes/kotlin/main/server.js

According to the NodeJS documentation:

Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory. (https://nodejs.org/api/modules.html#modules_require_id)

In our case __dirname is build/classes/kotlin/main

So the correct require statement is:

val serviceAccount = js("require('../../../resources/main/file.json')") 

or if require is defined as a Kotlin function like in the question

val serviceAccount = require("../../../resources/main/file.json") 
like image 75
Alexander Egger Avatar answered Oct 19 '22 04:10

Alexander Egger