Load resource file (json) in kotlin js
Asked Answered
A

2

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.

Aciculum answered 11/3, 2019 at 22:57 Comment(4)
Will this code run on the server side (NodeJS) or on the client side?Tiny
@AlexanderEgger server side, so the path is (easier) guaranteedAciculum
using gradle only wont help, use the kotlin-frontend-plugin as well, locate you file.json in the resources folder and watch the magic happenPension
you need something like json-loader plugin for webpack to load json with codeAday
T
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") 
Tiny answered 27/3, 2019 at 7:12 Comment(0)
T
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

Textbook answered 11/3, 2019 at 23:1 Comment(2)
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'Aciculum
I guess the ./file.json may help thenTextbook

© 2022 - 2024 — McMap. All rights reserved.