designdebt.club
Menu
Design Debt Club

Getting an embed’s full file path in Obsidian

While working on my Ink plugin for Obsidian, I was attempting to convert the embeds to work off standard SVG files, however, I was struggling to get the correct file path to the SVG file when interpreting the markdown.

A markdown embed looks like the below. You wouldn’t realise it but this test.svg sits in a folder call folder-name. Obsidian doesn’t put that part in because, in this case, it’s the only file in the vault with the name test.svg, so it knows it can figure out the path later.

![Description](test.svg)

The problem is, when I grabbed that path to try and show it with my custom html code. I didn’t know how to get the correct path myself. I ran it through the below functions, but they didn’t work as I expected.

// filepath = test.svg
const normedPath = normalizePath( filepath )
const fullPath = plugin.app.vault.adapter.getResourcePath( nPath );

The getResourcePath function converts the path to an absolute path on your hard drive, but it’s missing the folder name. You need to get the relative path to the vault root before passing it to getResourcePath.

/* Output */
app://239482395865/Users/username/vault-name/test-svg.svg

/* Should be */
app://239482395865/Users/username/vault-name/**folder-name**/test-svg.svg`

Note: normalizePath is used to handle any spaces and other odd characters in paths.

Solution

So how do you turn test.svg that the md file says into folder-name/test.svg ?

To do that, we use the getFirstLinkpathDest method to convert the path from a shortened path to a path relative to vault root. It also needs a reference to the markdown file that it is embedded in, or the folder it is relevant to. As Obsidian will look for the best match to that embed based on the context.

// filepath = test.svg
// mdFile = The TFile object of the markdown file that contains it.
const normedPath = normalizePath( filepath )
const embeddedFile = plugin.app.metadataCache.getFirstLinkpathDest(normedPath, mdFile)
let filepath: string | undefined
if(embeddedFile) {
    filepath = plugin.app.vault.getResourcePath(embeddedFile);
};

That’s it!