Daily Note script creating new file even when already exists

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

i have to ask… why are you running this script when this functionality is available natively?

Native functionality creates the file in 1 specific folder set in settings. I am trying to create it in further more levels by year and month dynamically. So using the script.

if I am missing something, kindly let me know.

If you’re using the Daily Notes core plugin, you can already create daily notes within nested folders (e.g.: YYYY/MM) :blush:

See the Automatic subfolders callout here: Daily notes - Obsidian Help

If I remember correctly, in the Daily Notes core plugin settings:

  • for New file location you would need to choose Daily

and then:

Edit: Now if that doesn’t satisfy your needs and you still need the Templater template … I would probably use something similar to this snippet: Create folder if it doesn’t exist (or check with tp.app.vault.getFolderByPath() :thinking: ) instead of app.vault.adapter...

2 Likes

Thank you so much. I never noticed this feature.

1 Like