An API function to get the full system file path for note / file without extra phrases or text encoding

Use case or problem

Write now the only way to get the system file path for a file / note is with app.vault.getResourcePath() and then process it. I use this JS to do so (created with the help of GPT 4):

let filePath = app.vault.getResourcePath(app.workspace.getActiveFile());
filePath = decodeURIComponent(resourceUrl.replace(/app:\/\/[^\/]+\//, '/').split('?')[0]);

Proposed solution

There should be a function like app.vault.getFilePath() to do the same thing but more concise.

getActiveFile() return a TFile, where you can get the full path with .path: TFile - Developer Documentation (and TAbstractFile - Developer Documentation)

2 Likes

I just tried let filePath = app.workspace.getActiveFile().path; in the console and it appears to only shows the path in the vault, not the whole OS file path. Does it work for you?

1 Like

Oh sorry, I didn’t understand you want the OS path!

There is already the vault.adapter.getFullPath() method on desktop. (Don’t forget the instanceof check)

2 Likes

Thanks I got it working now!

let filePath = app.vault.adapter.getFullPath(app.workspace.getActiveFile().name)

A small correction: namepath

let filePath = app.vault.adapter.getFullPath(app.workspace.getActiveFile().path)
2 Likes

Thanks!

In fact all that advices work in compiled JS. But TS doesn’t allow me to do that because

the proposed method getFullPath exist on type FileSystemAdapter, but vault.adapter is an instance of DataAdapter, which is a base type and doesn’t implement this method.

And I cannot instatiate FileSystemAdapter, as in compiled JS it accepts a basePath as the constructor parameter, which is missing in TS.

Do I get anything wrong about typing in the Obsidian API?

if (vault.adapter instanceof FileSystemAdapter) {
  const absolutePath = vault.adapter.getFullPath(file);
}

Thank you. But it’s not a real solution. It’s a hack, like the others in this theread. I still have something to write in the else section.

This is either a bug of typng or devs hid this functionality on purpose. We can do a lot with dynamic languages, but normally those kind of type checking are considered a bad practice (code smell).

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.