Geequlim / ECMAScript

Javascript binding for godotengine
MIT License
959 stars 84 forks source link

How should a file be accessed? #146

Open ogrotten opened 1 year ago

ogrotten commented 1 year 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?

why-try313 commented 1 year ago

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 a class with a contructor as value

In other words:

const godot = {
    File: class {
        constuctor(params) { ... }
        method_of_File_class() { ... }
    },
    CLASS_NAME: class { ... }
}
nmerget commented 11 months 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.