ECMAScript
ECMAScript copied to clipboard
How should a file be accessed?
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:
While trying to setup const file = new godot.File.new()
gives the error message:
.
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?
Calling godot.File.new
looks for a method inside the godot.File
class, which ends up calling as a function with new()
that doesn't exist.
godot.File
is the class, so any of godot's classes should be called with new godot.CLASS_NAME()
, or in this case, new godot.File()
godot
being the object,File
being a property that has aclass
with acontructor
as value
In other words:
const godot = {
File: class {
constuctor(params) { ... }
method_of_File_class() { ... }
},
CLASS_NAME: class { ... }
}
@ogrotten
I was able to set up a working example:
- I created a simple
.json
file - I created a singleton
- I add the singleton as autoload
- I imported the singleton. It has to be the same name you gave in the Project Settings.
- I called the function. This will give me the
Object
inside the.json
file so as a String you need to useJSON.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.