I did some google and looking through the docs, but the only function I could use is app.vault.modify()
to change the whole content of a note. While there is a Vault.append()
function, there isn’t one for prepending.
Obsidian should add a function for doing so, but for now this works:
// This adds the phrase "lorem Ipsum" to the top of a note if there's no frontmatter,
// or right below the fronmatter is present.
let file = app.workspace.getActiveFile();
let newFileContent = String(await app.vault.read(file));
let stringToPrepend = "lorem ipsum";
newFileContent = /^(---(.|\n)+?---)/.test(newFileContent) ? newFileContent.replace(/^(---(.|\n)+?---)/g, `$1\n${stringToPrepend}`) : `${stringToPrepend}\n${newFileContent}`;
app.vault.modify(file, newFileContent);