How to read a file from workspace

Hi all,

is there a way how I can access and read (ideally json) file in Theia worskpace programmatically?
I am trying several ways but I think I got somehow lost … so thank you for hints.

@CrixOv thanks for the discussion, you can inject and use the FileService to read a file, among other filesystem utilities. In order to determine the current workspace and other workspace-related information you can use the WorkspaceService.

Hi @vince-fugnitto,

thank you for your answer, I will investigate this

1 Like

Hi again,
so I am trying to access files through FileService as recommended, but now I am struggling with the Error TypeError: this.fileService is undefined.

I have this class:

class JsonReader {
@inject(FileService) protected readonly fileService: FileService;
async readJsonFile() {
const fileUrl: URI = new URI(
http://localhost:3000/#/c:/HIGHTEC/Development/THEIA/PokusneSoubory/emptyWorkspace.theia-workspace/hello.json
);
console.log(“This is readJsonFile method”);

if (!(await this.fileService.exists(fileUrl))) {
console.log(“Resource does not exist”);
this.fileService.createFile(fileUrl);
} else {
console.log(“Resource exists”);
}

const fileContent = await this.fileService.read(fileUrl);
console.log(“Filecontent read”);
return fileContent;
}

And I am trying to call it:

const reader = new JsonReader();
const fileContent = await reader.readJsonFile();

but it ends on the error mentionned above on the first line where this.fileService is used, currently this.fileService.exists(fileUrl)

I have read somewhere that I have to register FileSystemProvider but I dont know if it is the real answer to my issue.
Sorry for this dumb question, not only I am new to Theia, I am also new to TypeScript and the family around it so everything is pretty new for me :slight_smile:

Hi @CrixOv,

you are instantiating the JsonReader class using its constructor. This does not allow for dependency injection, which is the reason the fileService stays undefined. Instead, the JsonReader should be injected in the class which uses it (It needs to be decorated with @injectable() by the way). Something like this:

@injectable()
class SomeClass {
  @inject(JsonReader) protected readonly jsonReader: JsonReader;
  
  async doSomething(): Promise<void> {
    const jsonContent = await this.jsonReader.readJsonFile();
    ...
  }
}

Also, the FileService expects a file path to read from, not a web URL. So you would simply enter:

new URI().withPath("c:/HIGHTEC/Development/THEIA/PokusneSoubory/emptyWorkspace.theia-workspace/hello.json").withScheme("file");

There is a dangling promise which could also do some harm at this.fileService.createFile()

1 Like