Rename a file if already exists in javascript by increment file_1.txt,file_2.txt like that. This code didn’t works

I tried this code, It creates a file like file.txt as file_1.txt after that it didn’t increased it ,again i gave a filename as file.txt it again shows file_1.txt. I need to increase the value like file_1.txt,file_2.txt,file_3.txt like that.

 while (await client.exists(path+'/'+filename)) {
        var ext = filename.split('.');
        if (i == 0) {
            i = i + 1;
            filename = ext[0] + "_" + i + "." + ext[1]
            i++;
            var newfilename = filename
            // await client.put(buff,path+'/'+newfilename)
            console.log(newfilename)
           
        } else {
            file = ext[0].substr(0, ext[0].lastIndexOf("_" + i));
            i = i + 1;
            filename = filename + "_" + i + "." + ext[1]
        }

    }