godotjs / javascript

Javascript binding for godotengine
https://godotjs.github.io/
MIT License
980 stars 82 forks source link

How should a file be accessed? #146

Closed ogrotten closed 1 month ago

ogrotten commented 2 years ago

I have a configuration in JSON format. I want to read this file as an Autoload Singleton.

None of the file options work.

JS fetch() and FileReader() both give the same basic error message: image

While trying to setup const file = new godot.File.new() gives the error message: image.

Then I figured "well I'll just have a GDScript, at the top of the Autoload tree, that reads the file as text and passes it on" but the JSX script couldn't find the file/class/property. import {ReadJson} from "ReadJson" or `from "ReadJson.gd" would give an error like they couldn't find the file, and I tried several paths. I would have put a screen for the error here, but I couldn't regenerate the error or problem.

However, I would understand if "you can't" cross-use data between GD and JS. In retrospect, it seems pretty obvious heh.

The bottom line is that I'd like to read a file in JS as an Autoload Singleton. How should I do this?

nmerget commented 1 year ago

@ogrotten

I was able to set up a working example:

  1. I created a simple .json file
  2. I created a singleton
  3. I add the singleton as autoload
  4. I imported the singleton. It has to be the same name you gave in the Project Settings.
  5. I called the function. This will give me the Object inside the .json file so as a String you need to use JSON.stringify()

    I used TypeScript but it's the same in JS but without the types. One hint if you use TS I added resolveJsonModule to the ts-config.json.

    Another hint: I used esbuild --bundle to include dayjs from node_modules. But the file where I included the singleton used the resolved import for this. So I wasn't able to call the singleton because the autoload path in project settings wasn't in the test.jsx file anymore. The solution was to use another file to resolve all modules from npm as bundle and include this in every other file. I will add all of this to the new documentation and I will change the misc folder to have a working TS-project out of the box.

nmerget commented 1 month ago

Added two examples:

https://geequlim.github.io/ECMAScript/examples/load-json-in-singleton/ https://geequlim.github.io/ECMAScript/examples/read-file-local/