I developed a web component to upload all the files in the subfolders of a folder using an HTML Input with the webkitdirectory
attribute but I noticed a strange bug in the sort order of the subfolders when I iterate through the files list of the input using Javascript on different machines.
I tested on several machines running on Windows 10, 11, or Ubuntu 22 and the subfolders are sorted alphabetically in ascending order but on one specific Windows 11 machine, they were sorted in descending order.
Here is the Typescript code that handles the input:
const files = Array.from((event.target as HTMLInputElement).files || [])
const filesByDirectory = R.groupBy(files, (file) =>
file.webkitRelativePath.split("/").slice(0, -1).join("/")
)
for (const folder of filesByDirectory) {
await this.uploadFiles(filesByDirectory[folder], folder.split("/").pop() as string)
}
I thought that the default sorting order of the subfolders would always be consistent, alphabetical and ascending order, but it seems it isn't.
In the meantime I added a line to sort the folders list before uploading but still I would like to understand why is it different for that machine? And what is the underlying rule or default?
Indeed, the specs don't require any defined ordering, and it seems that browsers do defer to the OS to set that ordering.
On my macOS system I have an apparently arbitrary order: Files aren't sorted by name, nor by date modified or created, nor by size, nor by type, nor by any other rule that the OS file explorer (Finder) offers for sorting. But, all browsers do return that same order for the same folder.
So you shouldn't rely on any particular ordering and instead convert the FileList
object you receive to an Array
* and sort that as you wish.
* OP contains an example on how to do that.