How do you read a txt file to a string in the JS t...
# javascript
j
How do you read a txt file to a string in the JS target of a Kotlin Multiplatform project?
b
haven't tested it but https://stackoverflow.com/questions/9168737/read-a-text-file-using-node-js and
Copy code
kotlinext.js.require("fs").asDynamic().readFile(/*...*/)
should help you
long story short, the same way as in node
j
thanks I will try that!
yea I knew I needed readFile (or readFileSync), but couldn’t figure out how to call that method in my JS target code
How do I use
kotlinext
? Unresolved reference by default.
@Bruno_ ^
b
do you have the nodejs target setup?
j
yes - in my build.gradle.kts:
Copy code
[...]

js("nodeJs") {
    nodejs()
}

[...]
b
in the exmaple module the compiling succeeded but I got something "couldn't find fs module", maybe that'll help you https://github.com/mightybruno/kotlin-vue
g
@Justin Excuse my curiosity, but in what context does it make sense to use kotlin/JS inside nodejs (instead of a kotlin server like ktor)?
j
@gaetan I am building a library that targets iOS, Android, and Web clients. Library just contains business logic that we used to implement separately on all three platforms.
g
So your question is for the web client? How can it access files ?
j
for my situation, the clients themselves do not need to access files. the files are for internal testing. but that still means that each platform needs a method for ingesting the files
the solution i implemented for the js target was:
Copy code
actual fun readFile(filePath: String) : String? {
    val fs = js("require('fs')")
    return fs.readFileSync(filePath, "utf8") as? String
}
in case it helps anyone
g
Ok. I understand.
👍 1
296 Views