Templater testing if folder exists

What I’m trying to do

testing for the existence of a folder and creating the folder if it doesn’t exist.

Things I have tried

I tried this:

if (!tp.file.exists(yearLink)) {
	await app.vault.createFolder(dir)
}

It seems to work in one of my 3 vaults, but not the others (which makes no sense at all). @shabegom says it shouldn’t work (he said “exists” doesn’t work on folders).

As @shabegom suggested, I tried:

const exists = app.fileSystemAdapter.exists("yearLink")
if (!exists) {
    app.vault.createFolder(dir)
}

but the system says it can find the exists() function (I tried adding a boolean because the function definition seemed to say it was required, but it didn’t make any difference).

more detail

I have 3 vaults. I am using templater to create my daily notes. In my “Obsidian/journal/daily” folder, I have subfolders for each year (e.g., 2022). I want to create the daily note in the correct subfolder. However, the year subfolder is not guaranteed to exist (though if I can’t solve the issue with templater, I may just create a bunch of them and ignore the problem).

When I click on the date in the calendar, the daily note (named something like “2022-09-12” is created in the “Obsidian/Journal/daily” folder. I then check to see if the year folder (e.g., “2022”) exists. If it doesn’t, I want to create it. Once I’m sure it is there, I move the daily note to the year subfolder. Should be pretty straight forward. Here’s a snippet from the daily notes template (the journal folder does live in an “Obsidian” folder which is not the vault folder).

console.log(`tp.file.folder(true) = ${tp.file.folder(true)}`)
console.log(`yearLink = ${yearLink}`)
const dir = tp.file.folder(true) + "/" + yearLink;
console.log(`dir = ${dir}`)
console.log(`tp.file.exists(dir) = ${tp.file.exists(dir)}`)
console.log(`tp.file.exists(dir + "/") = ${tp.file.exists(dir + "/")}`)
console.log(`tp.file.exists(yearlink) = ${tp.file.exists(yearLink)}`)

if (!tp.file.exists(yearLink)) {
	await app.vault.createFolder(dir)
}
await tp.file.move(dir + "/" + title)

In the vault that works, I see in the developer log:

tp.file.folder(true) = Obsidian/Journal/daily
yearLink = 2022
dir = Obsidian/Journal/daily/2022
tp.file.exists(dir) = false
tp.file.exists(dir + "/") = false
tp.file.exists(yearlink) = true

and in the vault that doesn’t work, I see

tp.file.folder(true) = Obsidian/Journal/daily
yearLink = 2022
dir = Obsidian/Journal/daily/2022
tp.file.exists(dir) = false
tp.file.exists(dir + "/") = false
tp.file.exists(yearlink) = false
plugin:templater-obsidian:82 Templater Error: Template parsing error, aborting. 
 Folder already exists.
log_error @ plugin:templater-obsidian:82

Any suggestions are appreciated.

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