6

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.

Diolor
  • 13,181
  • 30
  • 111
  • 179

2 Answers2

5

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") 
Alexander Egger
  • 5,132
  • 1
  • 28
  • 42
0

You may just use js("require('./file.json')") if you do not have import for the require function in Kotlin. The result will be dynamic, so you may cast it to Map.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/js.html

Eugene Petrenko
  • 4,874
  • 27
  • 36
  • 3
    How will solve the issue? I see that either `require("file.json")` or `js("require('file.json')")` will generate the same javascript code: `require('file.json')`. The problem still remains that the file.json cannot be found in the path. To be precice with the exception: `Error: Cannot find module 'file.json'` – Diolor Mar 11 '19 at 23:14
  • I guess the `./file.json` may help then – Eugene Petrenko Mar 11 '19 at 23:16