Hi, I am new to js world. In Kotlin Js, how can I ...
# javascript
a
Hi, I am new to js world. In Kotlin Js, how can I read a 'resource' txt file? My guess is it has something to do with using
require
and some module system. Any tutorials or examples on the topic would be appreciated.
n
On the browser side (with the JS platform) file/directory access isn't permitted for security reasons ( https://stackoverflow.com/questions/371875/local-file-access-with-javascript ).
Server-side programs can access files/directories. If you had a web stack then the front-end would be able to communicate with the server (eg via HTTP) to obtain the contents of the text file (residing on the server).
Browser environments are stateless ( https://softwareengineering.stackexchange.com/questions/346867/how-to-keep-applications-stateless ), with a heavy reliance on servers (which are stateful) to manage state for front-end web applications.
a
I understand files on the system are not accessible, I mean to use files that are part of the "source code". Like the resources folder in java/maven world
g
On JS you don't have resources as part of source code, there is no jar format that allows you to do that. On js you have only source JS code (not even Kotlin code), so there is no simple replacement for Java-like resources. So, depending on your case you need some alternative solution (save resource as base64 to a string and save to some constant, upload it to CDN and download etc)
a
Thanks for the clarification. I thought there was a standard way that it is abstracted away by the compiler and I just didn't know how to use it
r
@aarjav you could achieve this by embedding the text file in the source code by leveraging webpack, which is a JS bundler that https://github.com/Kotlin/kotlin-frontend-plugin uses.
You could specify https://github.com/webpack-contrib/raw-loader as a dependency, then add a webpack code snippet to load it, then use it. This is all theorycraft though, haven’t tested, but that’s how I’d approach the problem
a
That sounds exactly like what I'm looking for, thanks!
g
I would just point that if you not very deep into JS build infrastructure, work with webpack maybe not so easy, it’s pretty big tool
also it always depends on your case, what kind resource do you need. Because use this solution for binary files is probably not a good idea
247 Views