There are two approaches I am aware of:
Unique folder names
By placing each file in a folder with a unique name, you can preserve the original file name and avoid any clashes. This method will make things much easier for you if you want to store associated files (e.g. image thumbnails) with the original.
You can generate unique folder names using a UUID, which is a string that is virtually guaranteed not to clash. There are plenty of Node.js libraries to generate a UUID, such as uuid. Or just use any random string and check if the folder already exists to be sure.
Alternatively, as in the example you gave, the folder names could be generated according to date and time, but you have to be sure that you will only add one item at one point in time, or add random folders under the date as in the iPhoto example. The dated folders in iPhoto are probably not necessary when they are also using random-strings as folder names, but they would make it friendly for a user who is manually browsing through the folders, and there may be performance benefits if iPhoto needs a directory listing for a specific date.
You need to store a reference to both the folder name and the file name in order to load the file, but of course this could be one string e.g. "6c84fb90-12c4-11e1-840d-7b25c5ee775a/image.jpg"
.
Unique file names
Another technique is to rename files to have a unique name whenever there is a clash. This is the approach used by the macOS Finder when you create new folders or duplicate a file. This approach is usually best if the user may interact directly with the files, as they will not have to navigate through folders with meaningless names.
As a simple example, let's say I am adding photos of penguins, and I've already added a photo called penguin.jpg
.
Now I add a second photo which also happens to be called penguin.jpg
.
- Check if
penguin.jpg
exists. It does, so...
- Generate a new name for the file,
penguin-2.jpg
- Check if
penguin-2.jpg
exists. It doesn't, so...
- Save the new file as
penguin-2.jpg
If I add more files also called penguin.jpg
, the program needs to keep incrementing the name until I find one which does not exist (e.g. penguin-3.jpg
). This should not cause any performance issues unless adding thousands of files with the same name (which seems unlikely).
I found a Node.js module which can handle this approach for you: uniquefilename