JavaScript How do you properly check if filename exist and generate a suffix before writing it to the directory?

I have a function that writes a file to a directory:

response.pipe(fs.createWriteStream(fullPath))

But before that I want to check if the path already exist, and if so, add a suffix, e.g. file_1.txt (and if that exist, create file_2.txt instead...etc):

// Check if the path already exist
let fullPath = "C:/test/file.txt"
let dir = "C:/test/"
let fileName = "file" 
let fileExt = ".txt"

if (fs.existsSync(fullPath)) {
  // I tried using a while loop but I end up making it too complicated
  ...
}


// Write file to disk
response.pipe(fs.createWriteStream(destinationPath))

Question

How do I properly / efficiently do that?

Answer:1

The while loop is the correct way.

// Check if the path already exist
let fullPath = "C:/test/file.txt"
let dir = "C:/test/"
let fileName = "file" 
let fileExt = ".txt"
let num = 0;

while (fs.existsSync(fullPath)) {
  fullPath = `${dir}${fileName}_${num++}${fileExt}`;
}

After this, fullPath contains the first nonexistent file.

Note that there's a potential race condition. Some other process could create the file after your loop finishes.

Answer:2

If all of your file names are named the same thing + "_#".txt, I think the most (one of the most) efficient ways to check that would be something along the lines of:

Get all files from the directory

var files = [];
fs.readdir(dir, (err, files) => {
  files.forEach(file => {
    files.push(file);
  });
})

You would then sort the array (could be expensive if a lot of files)... then last record would be the highest number which you can easily extract.

Another thing you could do is find the file which has the latest creation date using similar approach using the Stats class from FS.

Answer:3

I have the following markup: <li data-group="bottoms">Pants</li> <li data-group="bottoms">Pants</li> <li data-group="bottoms">Pants</li> <li data-group="tops"&...

I have the following markup: <li data-group="bottoms">Pants</li> <li data-group="bottoms">Pants</li> <li data-group="bottoms">Pants</li> <li data-group="tops"&...

  1. returning unique values from a list in excel
  2. sql return unique values

I am writing an Android app that requires access to a MySql server. Following examples I have found, I have a php page that sits on the server and does the MySql stuff, and I try to access that from ...

I am writing an Android app that requires access to a MySql server. Following examples I have found, I have a php page that sits on the server and does the MySql stuff, and I try to access that from ...

  1. android gets hot
  2. android gets hot while charging
  3. android gets slower over time
  4. android gets hot and battery drains
  5. android gets citizenship
  6. android gets ads
  7. android gets stuck on boot screen
  8. android gets hacked
  9. android gets virus
  10. android gets fido2 certification
  11. android gets slow sometimes
  12. android gets black screen
  13. android get iphone apps
  14. android gets focus
  15. android gets stuck on startup
  16. android gets screen width
  17. android gets lag
  18. android phone gets hot
  19. android auto gets disconnected
  20. android 18 gets absorbed by cell

I have a map like this for example const Map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]); /* The structure of the Map looks like this: Map {...

I have a map like this for example const Map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]); /* The structure of the Map looks like this: Map {...

I have a navbar which needs to change colour on scroll. This functionality was originally built with js, however now it has a 'Login' button which is built in elm to perform other functionality. I ...

I have a navbar which needs to change colour on scroll. This functionality was originally built with js, however now it has a 'Login' button which is built in elm to perform other functionality. I ...