Skip to content

Create a folder, move file to it and add check list #569

carlosbaraza started this conversation in Templates Showcase
Create a folder, move file to it and add check list #569
Feb 23, 2022 · 1 comments · 1 reply

Every time I travel, I complete a checklist, and I like to have a folder to to add all my tickets and other resources, so everything is organised.

The following template does:

  • Create a Resources/Travel/YYYY-MM-DD and Resources/Travel/YYYY-MM-DD/_resources folders
  • Move the file to the folder and rename to Travel Checklist
  • Add the template checklist
<%*
    // YYYY-MM-DD
    function formatDate(date) {
        let d = new Date(date);
        let month = '' + (d.getMonth() + 1);
        let day = '' + d.getDate();
        let year = d.getFullYear();

        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;

        return [year, month, day].join('-');
    }

    async function createFolder(dir, times = 1) {
        if (times > 5) {
            throw new Error('createFolder: too many tries');
        }
        try {
            let newDir = dir;
            if (times > 1) newDir = `${dir} (${times})`;
            await this.app.vault.createFolder(newDir);
            return newDir;
        } catch (err) {
            return createFolder(dir, times + 1);
        }
    }

    const today = formatDate(new Date());
    let dir = `Resources/Travel/${today}`;
    dir = await createFolder(dir);
    const resourcesFolder = `${dir}/_resources`;
    await createFolder(resourcesFolder);

    await tp.file.move(`${dir}/Travel Checklist`);
%>
- [ ] Keys to come back
- [ ] Check in
- [ ] Sun cream
- [ ] Glasses

Clothes
- [ ] Underwear

Replies

1 comment
·
1 reply

I think this can be simplified to:

<%*
let dir = "Resources/Travel/" + tp.date.now("YYYY-MM-DD");
await this.app.vault.createFolder(dir);
this.app.vault.createFolder(dir + "/_resources");
tp.file.move(dir + "/Travel Checklist");
%>
- [ ] Keys to come back
- [ ] Check in
- [ ] Sun cream
- [ ] Glasses

Clothes
- [ ] Underwear
1 reply
@carlosbaraza

The tp.date.now() is a good trick. However, the this.app.vault.createFolder(dir) will fail if the folder already exists. And the tp.exists function is only detecting files, not folders. My workaround is to create a new folder with the suffix (number) when another folder already exists.

It would be great if we had a complete node fs implementation to check files, folders, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants