What I’m trying to do
I am trying to create a script in a template file to create daily note in a specific folder based on the date of creation. When running the first time, it is working fine. But when run second time, it is not opening the already created file, but keep creating the file in the root directory. Strangely, when run the third time, it opens the file created in the root directory that was created in the second run.
How to make the script open the file created on the first instance when run consecutive times.
Here is the script:
<%*
/* ========= SETTINGS ========= */
const ROOT = "/Daily";
const DATE = tp.file.creation_date; // creation date (not “now”)
/* ========= PATH COMPONENTS ========= */
const file = tp.file.title;
const year = DATE("YYYY"); // 2025
const month = DATE("MM-MMM").toUpperCase(); // 06-JUN → 06-JUN
const yearDir = `${ROOT}/${year}`; // Daily/2025
const monthDir = `${yearDir}/${month}`; // Daily/2025/06-JUN
const target = `${monthDir}/${file}`; // full file path (no .md)
/* ========= HELPERS ========= */
async function ensureFolder(path) {
if (!(await app.vault.adapter.exists(path))) { // adapter.exists is async & case-insensitive
await app.vault.createFolder(path); // creates the folder
}
}
/* ========== EXECUTION ========== */
if (!(await tp.file.exists(target + ".md"))) {
await ensureFolder(yearDir); // make year folder if needed
await ensureFolder(monthDir); // make month folder if needed
await tp.file.move(target); // move to organized location
} else {
console.log("File already exists");
const pathTFile = app.vault.getAbstractFileByPath(target + '.md');
app.workspace.getLeaf(false).openFile(pathTFile);
}
%>
Thanks,
Immanuel Michael

