Check for existing file with same name and create new name?

I’m trying to export a bunch of drafts, some of which may have the same. Does anyone have any existing code that checks whether a file with that name has been created, and if so, adds an integer or something to the draft title before writing to a new file?

FileManager object does not have an exists function. That would be a good addition, will make a note to add.

Right now, I would say you have two options:

  1. If you are only concerned with consistency in your export batch, just keep up with the names you have written already, and compare against it.
  2. If you are worried about files that may already be there in the directory before you run your action, you would have to call FileManager.listContents on your directory path, and then check if it contains the path you are about to write.

For 1, I’d do something like (untested):

// query for your drafts to export
let drafts = Draft.query(...);

// create your FileManager
let fm = FileManager.createCloud();

// create object to keep up with written files
let written = {};

// loop over drafts you are exporting...assume you put them in `drafts` variable
for (let d of drafts) {
    let path = d.processTemplate("your/path/[[safe_title]].txt");
    let existing = written[path];
    if(existing) { // we already wrote to this path
        existing++; // increment counter
        path = d.processTemplate(`your/path/[[safe_title]] - ${existing}.txt`); // update path
        written[path] = existing;
    }
    else { // we have not written to this path - add counter for it
        written[path] = 0;
    }
    fm.writeString(path, d.content);
}

That should get you something like this for conflicts:

Title.txt
Title - 1.txt
Title - 2.txt

a few small changes, but this was a good approach. Thanks!

for (d of files)
{
    // Create title if draft has a blank first line
    let i = d.processTemplate("[[safe_title]]").replace("# ",""); // Feel free to change this replace formula if your files don't start with a markdown hash header
    console.log("title: " + i)
    if (i.length == 0)
    {
        i = "Draft " + j;
        j++
    }
let title = i; 
let existing = written[title];
    if(existing || written.hasOwnProperty(title)) { // we already wrote to this path
        existing++; // increment counter
        written[title] = existing;
        title = title +" - " +existing; // update path
    }
    else { // we have not written to this path - add counter for it
        written[title] = 0;
    }

1 Like