@@ -437,23 +437,31 @@ async function getStorageFolder(
437437 }
438438
439439 const realpath = await fs_realpath ( storagePath ) ;
440- let folderName = join ( realpath , lastName ) ;
440+ let folderName = lastName ;
441+
442+ // get all existing files instead of calling pathExists on every
443+ // single combination of realpath and folderName
444+ const existingFiles = await readdir ( realpath ) ;
441445
442446 // avoid overwriting existing folders
443447 let counter = 0 ;
444- while ( await pathExists ( folderName ) ) {
448+ while ( existingFiles . includes ( basename ( folderName ) ) ) {
445449 counter ++ ;
446- folderName = join ( realpath , `${ lastName } -${ counter } ` ) ;
447- if ( counter > 100 ) {
448- // If there are more than 100 similarly named databases,
450+ folderName = `${ lastName } -${ counter } ` ;
451+ if ( counter > 10_000 ) {
452+ // If there are more than 10,000 similarly named databases,
449453 // give up on using a counter and use a random string instead.
450- folderName = join ( realpath , `${ lastName } -${ nanoid ( ) } ` ) ;
454+ folderName = `${ lastName } -${ nanoid ( ) } ` ;
451455 }
452- if ( counter > 200 ) {
453- throw new Error ( "Could not find a unique name for downloaded database." ) ;
456+ if ( counter > 20_000 ) {
457+ // This should never happen, but just in case, we don't want to
458+ // get stuck in an infinite loop.
459+ throw new Error (
460+ "Could not find a unique name for downloaded database. Please remove some databases and try again." ,
461+ ) ;
454462 }
455463 }
456- return folderName ;
464+ return join ( realpath , folderName ) ;
457465}
458466
459467function validateUrl ( databaseUrl : string ) {
0 commit comments