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.

4
  • Will this code run on the server side (NodeJS) or on the client side? Commented Mar 26, 2019 at 19:34
  • @AlexanderEgger server side, so the path is (easier) guaranteed Commented Mar 26, 2019 at 21:31
  • using gradle only wont help, use the kotlin-frontend-plugin as well, locate you file.json in the resources folder and watch the magic happen Commented Apr 21, 2019 at 13:55
  • you need something like json-loader plugin for webpack to load json with code Commented Jul 8, 2020 at 9:08

2 Answers 2

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") 
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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'
I guess the ./file.json may help then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.