'exists' is undefined when using Vault.create()

Note: this is my first attempt to create a plugin in Obsidian - sorry if the mistake is obvious and I missed something key.

I am trying to create a file daylies.md in a test vault, based on the obsidian-sample-plugin, via:

export default class DayliesPlugin extends Plugin {
	settings: MyPluginSettings;

	async onload() {
		await this.loadSettings();
		const vault = new Vault();

		// check if the dailies file exists and create it if not
		if (vault.getFileByPath("daylies.md") === null) {
			console.log("daylies.md does not exist, creating");
			vault
				.create("daylies.md", "")
				.then(() => console.log("daylies.md created"))
				.catch((err) =>
					console.error(`cannot create daylies.md: ${err}`)
				);
		} else {
			console.log("daylies.md exist");
		}

(...)

What I get in the console (without the catch() to give a full picture):

daylies.md does not exist, creating
app.js:1 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'exists')
    at t.<anonymous> (app.js:1:732758)
    at app.js:1:237228
    at Object.next (app.js:1:237333)
    at app.js:1:236249
    at new Promise (<anonymous>)
    at g (app.js:1:235994)
    at t.create (app.js:1:732617)
    at DayliesPlugin.onload (VM267 plugin:daylies:40:13)

Any idea where the problem could be?

EDIT/ I also tried the async/await version - same thing.

OK, found it. I should not instantiate a new Vault() but use this.app.vault

const vault = new Vault();

You are not supposed to create an instance of Vault. You are supposed to access the Vault instance using this.app.vault. If you are using Typescript, this should have failed to compile since Vault does not have a public constructor that you can use.

You are not supposed to create an instance of Vault

Thank you @liam . I realized that while you were typing :slight_smile:

If you are using Typescript, this should have failed to compile since Vault does not have a public constructor that you can use.

I did not have any errors during the compilation (I do use TypeScript), just when accessing the method during run.

No new Vault() won’t fail in TypeScript, because as there is no constructor in typings, the default parameterless is assumed.

I think it’s quite confusing. We discussed it and I provided my idea how to address it MarkdownPreviewView has invalid constructor in the docs - #3 by mnaoumov

1 Like

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